iosnsdatensdateformatternsdatadetector

iOS NSDataDetector swapping AM hours to PM hours (Both should be 24 hours)


I am using NSDataDetector to read and swap an NSString Date / Time into an NSDate.

The input (lastRefreshStampString) is 2014-05-05 02:54:45 +0000 however, once it has been processed by NSDataDetector, result.date becomes 2014-05-05 14:54:45 +0000. For some reason it is seeing the 02 as PM and swapping it.

How can I correct this behaviour?

NSLog(@"lastRef:%@",lastRefreshStampString);

            __block NSDate *lastRefreshStamp;

            //Detect data format
            NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil];
            [detector enumerateMatchesInString:lastRefreshStampString
                                       options:kNilOptions
                                         range:NSMakeRange(0, [lastRefreshStampString length])
                                    usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
             { lastRefreshStamp = result.date; }];

            NSLog(@"lastRef:%@",lastRefreshStamp);

Solution

  • Because the timezone is different. NSDataDetector use the GTM , but your system timezone is not (I guess...).

    I have a test like you , and it output like this : enter image description here

    So , you can use NSDateFormatter the NSDateFormatter's default timezone is the same as the system timezone , so you can get the right date.

    NSString *lastRefreshStampString = @"2014-05-05 02:54:45 +0000";
    
    NSLog(@"lastRefString:%@",lastRefreshStampString);
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
    
    NSLog(@"time zone : %@",dateFormatter.timeZone.name);
    NSLog(@"system time zone : %@",[NSTimeZone systemTimeZone].name);
    
    NSDate *lastRefreshStamp = [dateFormatter dateFromString:lastRefreshStampString];
    
    NSLog(@"lastRef:%@",lastRefreshStamp);
    

    The output is right : enter image description here