Question

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);
Was it helpful?

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

OTHER TIPS

Do not use NSDataDetector to parse fixed-format dates. NSDataDetector has tons of heuristics to make date detection work better in the normal user's text content. It's not suited to parse dates that are not in natural language. Use NSDateFormatter for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top