6

I just noticed that NSDate *nowDate = [NSDate date]; gives me GMT+0 Time and not the local time. So basically on my iPad it's 13:00 and the output of this code is 12:00.

How do I get local time properly?

Jacek Kwiecień
  • 12,397
  • 20
  • 85
  • 157
  • Try this link, it allows you to get local time zone. http://buildingmyworld.wordpress.com/2011/04/13/get-local-time-from-iphone-local-nsdate/ – Adrian P Mar 25 '13 at 13:14
  • How are you getting the "output of this code"? Are you using an NSDateFormatter to get a string or are you just `NSLog`ging the NSDate object? – colincameron Mar 25 '13 at 16:34

4 Answers4

28

Give it a Shot !

NSDate* sourceDate = [NSDate date];

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];//use `[NSTimeZone localTimeZone]` if your users will be changing time-zones. 

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];

It will give you the time according to the current system timezone.

Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
Rajan Balana
  • 3,775
  • 25
  • 42
6

NSDate does not care about timezones. It simply records a moment in time.

You should set the local timezone when using the NSDateFormatter to get a string representation of the date:

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; // Set date and time styles
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateString = [dateFormatter stringFromDate:date];
colincameron
  • 2,696
  • 4
  • 23
  • 46
5
 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
 [calendar setTimeZone:[NSTimeZone localTimeZone]];
 NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
 NSDate *d = [calendar dateFromComponents:dateComponents];
wrtsprt
  • 5,319
  • 4
  • 21
  • 30
ahwulf
  • 2,584
  • 15
  • 29
4
// get current date/time
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter release];
NSLog(@"%@",currentTime);
iPatel
  • 46,010
  • 16
  • 115
  • 137