This line:
NSLog(@"date: %d",(int)[[NSDate date] descriptionWithLocale:currentLocale]);
is so wrong it hurts my head. The returned data from descriptionWithLocale
is an NSString *
, not an NSTimeInterval
, printing it as an int
is just converting a pointer to an int
, which is a bad idea at the best of times.
I'm presuming that your server is returning a timestamp that is #seconds after 1970 as well, so I just hard-coded an example of that in this piece of code:
NSLocale* currentLocale = [NSLocale currentLocale];
NSTimeInterval nsti = [[NSDate date] timeIntervalSince1970];
NSLog(@"date (as seconds from 1970): %ld", (long)nsti);
NSLog(@"date (as locale-relative string): %@", [[NSDate dateWithTimeIntervalSince1970:nsti] descriptionWithLocale:currentLocale]);
// This is Mon 25 Aug 2014, 20:17:51 BST (UTC +0100) obtained by date +%s, subtracting 60,000
NSTimeInterval time_from_server = 1408994271;
NSLog(@"date (from server as string): %@", [[NSDate dateWithTimeIntervalSince1970:time_from_server] descriptionWithLocale:currentLocale]);
Note, however that neither an NSDate
or an NSTimeInterval
have any concept of a timezone, and thus don't have a concept of an offset from GMT. What you need for that is an NSTimeZone
. Bearing in mind that the offset from GMT
depends on the current date/time (e.g. summer-time, winter-time), you have to use code like the following:
NSTimeZone *localZone = [NSTimeZone localTimeZone];
NSDate *date111 = [NSDate date];
NSInteger delta = [localZone secondsFromGMTForDate:date111];
NSLog(@"date= %ld", (long)delta);
Get the timezone, get the date, get the offset from GMT for the date, log it.
Displaying time as a specific timezone's local time:
NSTimeZone *phoenix = [NSTimeZone timeZoneWithName:@"America/Phoenix"];
NSTimeZone *dublin = [NSTimeZone timeZoneWithName:@"Europe/Dublin"];
NSTimeZone *tokyo = [NSTimeZone timeZoneWithName:@"Asia/Tokyo"];
NSDate *date111 = [NSDate date];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateStyle:NSDateFormatterFullStyle];
[fmt setTimeStyle:NSDateFormatterFullStyle];
[fmt setLocale:[NSLocale currentLocale]];
[fmt setTimeZone:phoenix];
NSLog(@"phoenix %@", [fmt stringFromDate:date111]);
[fmt setTimeZone:dublin];
NSLog(@"dublin %@", [fmt stringFromDate:date111]);
[fmt setTimeZone:tokyo];
NSLog(@"tokyo %@", [fmt stringFromDate:date111]);
Gives me (as of now):
phoenix Tuesday, August 26, 2014 at 9:33:12 AM Mountain Standard Time
dublin Tuesday, August 26, 2014 at 5:33:12 PM Irish Summer Time
tokyo Wednesday, August 27, 2014 at 1:33:12 AM Japan Standard Time
The fundamental concepts here are:
- NSDate doesn't have a concept of a timezone
- NSTimeInterval doesn't have a concept of a timezone
- Only the act of formatting a time for display needs a timezone
So with that in mind, when you get device time it's just either an NSDate or an NSTimeInterval which means that it does not encode the timezone into it.