How to get local time on iOS

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

How to get the local time?

+6
source share
4 answers

Take a picture!

 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]; 

This will give you time according to the current system time zone.

+28
source

NSDate does not care about time zones. It just records a moment in time.

You must set the local time zone when using 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]; 
+6
source
 // get current date/time NSDate *today = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // display in 12HR/24HR (ie 11:25PM or 23:25) format according to User Settings [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; NSString *currentTime = [dateFormatter stringFromDate:today]; [dateFormatter release]; NSLog(@"%@",currentTime); 
+4
source
  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]; 
+3
source

All Articles