Problem: [NSDate date] returns current time in GMT time zone. The question is how to get local time on users iPhone?
Description:
The question is quite straight forward so description will be short. When i encountered this problem I was amazed how hard it was to find an answer on the net. But fortunately I found a way to first get the local (system) time zone and then convert it to NSDate. Before I proved code that solves this problem I would like to point out that using GMT time zone is a common practice so if you’re storing your data in different time zone you have to be aware that it might cause incompatibility with 3rd party software. Just keep that in mind.
Solution:
NSDate* sourceDate = [NSDate date]; NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone]; NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate]; NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate]; NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset; NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
First thing we do is get the GMT time zone and our system time zone. After that offset for each time zone is calculated. Difference in offset is used to create new date with time interval. Basically what happens is your [NSDate date] is “shifted” to correspond to local system time zone.
Hope this helps. All comments are welcomed. I publish all my blog notifications on my twitter so if you wanna you can follow me @ http://twitter.com/PavlovicMario
Thanks alot!!!
Awesome! Very helpful.
Very Helpful, thanks a lot ;))
Thank you sooo much!
Nice one.
Thank you very much!!
Thanks a lot
Thank you, sir!
Just what i needed.
Hmm, this is technically wrong since NSDate actually represents the number of seconds that have elapsed since 2001-01-01.
Thank you very much!
Merci beaucoup 🙂
thanks a lot… it helps for me…