Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get local time on iOS [duplicate]

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?

like image 530
Jacek Kwiecień Avatar asked Mar 25 '13 13:03

Jacek Kwiecień


3 Answers

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.

like image 53
Rajan Balana Avatar answered Oct 12 '22 06:10

Rajan Balana


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];
like image 25
colincameron Avatar answered Oct 12 '22 08:10

colincameron


 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];
like image 38
ahwulf Avatar answered Oct 12 '22 07:10

ahwulf