1

I have a question about how timezone in [NSDate date] works. In my app, I am making a PUT web service call in which I have to send in the date in UTC, converted to milliseconds.

-(NSNumber *) dateToMillis: (NSDate *) date
{
   long long val = (long long)[date timeIntervalSince1970] *1000.0;
   return @(val);
} 

NSDate *date = [NSDate date];
NSLog(@"Date - %@", [self dateToMillis:date]);

NSTimeInterval timeZoneSeconds = [[NSTimeZone timeZoneWithName:@"CST"] secondsFromGMT];
NSDate *dateInUTC = [date dateByAddingTimeInterval:timeZoneSeconds];   
NSLog(@"Date UTC - %@", [self dateToMillis:dateInUTC]);

I assumed [NSDate date] would be in local timezone (CST) and tried to convert it to UTC, but both NSlogs print exactly the same value.

Does [NSDate date] not return the date time in local timezone?

Richa
  • 238
  • 1
  • 3
  • 16

3 Answers3

4

An NSDate represents a point in the continuum of time, which is independent of time zones or locale. Looking at that date in a time zone is a "view" of that time (i.e. "what do WE call that time in the temporal continuum?").

If your goal is to show a time in your current time zone, look at NSDateFormatter: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/ - you can set the time-zone (and the locale, if you want) to display in the formatter, and it will show you what that date is referred to as in that time zone / locale.

  • So irritated that I couldn't remember my password when answering this online earlier, so I had to be a guest to answer it :( – iAdjunct Jul 24 '15 at 00:48
4

NSDate has no concept of a timezone. It is created when you use [NSDate date] as the number of seconds in GMT from January 1, 2001. In order to create or print dates in your own timezone, you need to use NSDateFormatter methods to adjust this date for your timezone.

This answer goes over the concepts behind NSDate quite nicely.

Community
  • 1
  • 1
willrichman
  • 483
  • 4
  • 15
1

What Adjunct responds is correct, but in your case, the two response are equals because you are comparing two equal "time values". It is independent of Timezone.

Ostanik
  • 104
  • 1
  • 5