Converting NSString to NSDate (and back again)

后端 未结 17 2508
-上瘾入骨i
-上瘾入骨i 2020-11-21 23:26

How would I convert an NSString like \"01/02/10\" (meaning 1st February 2010) into an NSDate? And how could I turn the NSDat

17条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 00:04

    UPDATE 2019 (Swift 4):

    Made a Date extension for that. It uses NSDataDetector instead of NSDateFormatter.

    // Just throw at it without any format.
    var date: Date? = Date.FromString("02-14-2019 17:05:05")
    

    Pretty enjoyable, it even recognizes things like "Tomorrow at 5".

    XCTAssertEqual(Date.FromString("2019-02-14"),                    Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019.02.14"),                    Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019/02/14"),                    Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019 Feb 14"),                   Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019 Feb 14th"),                 Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("20190214"),                      Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("02-14-2019"),                    Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("02.14.2019 5:00 PM"),            Date.FromCalendar(2019, 2, 14, 17))
    XCTAssertEqual(Date.FromString("02/14/2019 17:00"),              Date.FromCalendar(2019, 2, 14, 17))
    XCTAssertEqual(Date.FromString("14 February 2019 at 5 hour"),    Date.FromCalendar(2019, 2, 14, 17))
    XCTAssertEqual(Date.FromString("02-14-2019 17:05:05"),           Date.FromCalendar(2019, 2, 14, 17, 05, 05))
    XCTAssertEqual(Date.FromString("17:05, 14 February 2019 (UTC)"), Date.FromCalendar(2019, 2, 14, 17, 05))
    XCTAssertEqual(Date.FromString("02-14-2019 17:05:05 GMT"),       Date.FromCalendar(2019, 2, 14, 17, 05, 05))
    XCTAssertEqual(Date.FromString("02-13-2019 Tomorrow"),           Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019 Feb 14th Tomorrow at 5"),   Date.FromCalendar(2019, 2, 14, 17))
    

    Goes like:

    extension Date
    {
    
    
        public static func FromString(_ dateString: String) -> Date?
        {
            // Date detector.
            let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
    
            // Enumerate matches.
            var matchedDate: Date?
            var matchedTimeZone: TimeZone?
            detector.enumerateMatches(
                in: dateString,
                options: [],
                range: NSRange(location: 0, length: dateString.utf16.count),
                using:
                {
                    (eachResult, _, _) in
    
                    // Lookup matches.
                    matchedDate = eachResult?.date
                    matchedTimeZone = eachResult?.timeZone
    
                    // Convert to GMT (!) if no timezone detected.
                    if matchedTimeZone == nil, let detectedDate = matchedDate
                    { matchedDate = Calendar.current.date(byAdding: .second, value: TimeZone.current.secondsFromGMT(), to: detectedDate)! }
            })
    
            // Result.
            return matchedDate
        }
    }
    

    UPDATE 2014:

    Made an NSString extension for that.

    // Simple as this.   
    date = dateString.dateValue;
    

    Thanks to NSDataDetector, it recognizes a whole lot of format.

    '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>
    

    Part of eppz!kit, grab the category NSString+EPPZKit.h from GitHub.


    ORIGINAL ANSWER 2013:

    Whether you're not sure (or don't care) about the date format contained in the string, use NSDataDetector for parsing date.

    //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; }];
    

提交回复
热议问题