1

I need to get NSDate with time zone @"UTC".

NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = @"MM/dd/yyyy HH:mm:ss aaa";;
NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
[dateFormatter setTimeZone:timeZone];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"time stamp %@", dateString);
NSLog(@"NSDate %@", [dateFormatter dateFromString:dateString]);

The output console prints different date:

time stamp 07/01/2014 06:12:54 AM

NSDate 2014-07-01 00:12:54 +0000

My question is, why the two timings are different even though using the same time zone:

jailani
  • 2,260
  • 2
  • 21
  • 45
  • 1
    see this posts http://stackoverflow.com/questions/11273001/nsdateformatter-datefromstring-returns-incorrect-date, http://stackoverflow.com/questions/7485493/get-nsdate-from-nsdate-adjusted-with-timezone – Mani Jul 01 '14 at 06:40
  • interesting. I tested without putting timezone, still different. but my theory is the `NSDate` printed there is using +0000 GMT, hence the printed `NSString` using current format / timezone. – HelmiB Jul 01 '14 at 06:46
  • I think you are confusing what `NSDate` is. `NSDate` represents an absolute point in time and is not related to any timezone. The `NSDate` description (which is the string representation that you're logging) is fairly arbitrary and not reliable across OS versions. The links provided at the first reply elaborate much further on that matter. In a nutshell: If you want human readable dates use `NSDateFormatter`; if you want to perform absolute time calculations use `NSDate` – spassas Jul 01 '14 at 08:50

0 Answers0