Thực hiện một số Tiện ích mở rộng NSString cho điều đó.
// Simple as this.
date = dateString.dateValue;
Nhờ có NSDataDetector, nó nhận ra rất nhiều định dạng.
// Tested in GMT+1 (Hungary).
@"2014-01-16" dateValue is <2014-01-16 11:00:00 +0000>
@"2014.01.16" dateValue is <2014-01-16 11:00:00 +0000>
@"2014/01/16" dateValue is <2014-01-16 11:00:00 +0000>
@"2014 Jan 16" dateValue is <2014-01-16 11:00:00 +0000>
@"2014 Jan 16th" dateValue is <2014-01-16 11:00:00 +0000>
@"20140116" dateValue is <2014-01-16 11:00:00 +0000>
@"01-16-2014" dateValue is <2014-01-16 11:00:00 +0000>
@"01.16.2014" dateValue is <2014-01-16 11:00:00 +0000>
@"01/16/2014" dateValue is <2014-01-16 11:00:00 +0000>
@"16 January 2014" dateValue is <2014-01-16 11:00:00 +0000>
@"01-16-2014 17:05:05" dateValue is <2014-01-16 16:05:05 +0000>
@"01-16-2014 T 17:05:05 UTC" dateValue is <2014-01-16 17:05:05 +0000>
@"17:05, 1 January 2014 (UTC)" dateValue is <2014-01-01 16:05:00 +0000>
Một phần của eppz!kit, lấy danh mục NSString+EPPZKit.h từ GitHub.
ĐÁP ORIGINAL: Cho dù bạn không chắc chắn (hoặc chỉ cần không quan tâm) về định dạng ngày chứa trong chuỗi, sử dụng NSDataDetector cho ngày phân tích cú pháp.
//Role players.
NSString *dateString = @"Wed, 03 Jul 2013 02:16:02 -0700";
__block NSDate *detectedDate;
//Detect.
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil];
[detector enumerateMatchesInString:dateString
options:kNilOptions
range:NSMakeRange(0, [dateString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{ detectedDate = result.date; }];
Chỉ hoạt động tốt – Minar
Unicode UTF-8 hoạt động tốt trong nguồn. – Jonny
Điều đó đã thay đổi khi di chuyển sang các trình biên dịch mới hơn kể từ khi tôi viết câu trả lời gốc của mình (https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/CreatingStrings.html#//apple_ref/doc/ uid/20000148-SW1). –