0

I need to get UTC date by specified NSDate. The problem is that utcDate doesn't calculates properly if date was in daylight saving period.

Here is a code I use:

NSDate *localDate = [updatesInfo objectForKey:@"date"];

NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
NSDate *utcDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];

UPD:

I read localDate from /Library/Receipts/InstallHistory.plist It's an OSX file which contains all application's installation history. https://www.dropbox.com/s/3pc178avr4pj7uj/1.png?dl=0

Serge
  • 2,031
  • 3
  • 33
  • 56

2 Answers2

1

NSDate is in UTC. Always.

The code that you posted seems to indicate that your "updatesInfo" contains an incorrect NSDate. Or at least you think it contains an incorrect date.

You may have made a mistake when you created the date. As a partial workaround, you can try using secondsFromGMTForDate: which will be correct most of the time, except for some dates very close to the point where DST changed (because the date you have isn't correct). You can improve on that:

NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMTForDate:localDate];
NSDate* betterDate = [localDate dateByAddingTimeInterval: -timeZoneOffset];
timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMTForDate:betterDate];
NSDate* utcDate = [localDate dateByAddingTimeInterval: -timeZoneOffset];
gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • I read localDate from plist: /Library/Receipts/InstallHistory.plist And it displays properly – Serge Sep 17 '14 at 11:43
  • a NSDate just wraps the number of secs since 1970. it IS in UTC. Only if you created it there could be an issue.. but thats upon creation – Daij-Djan Sep 17 '14 at 11:46
  • It stores date with my local zone and when debug it reads properly as is in plist: https://www.dropbox.com/s/3pc178avr4pj7uj/1.png?dl=0 – Serge Sep 17 '14 at 11:52
0

A property list file stores a date in UTC. If you open the file in a plain text editor you will see something like

<key>date</key>
<date>2014-07-08T09:30:15Z</date>

which is "2014-07-08 09:30:15 UTC". Therefore

NSDate *date = [updatesInfo objectForKey:@"date"];

should contain the correct date and there is no need to adjust that for your local time zone.

But note that the Xcode property list editor displays the date stored in the property list file according to your local time zone. And if you edit a date field in Xcode, it will be translated back to UTC for storage in the plist file.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382