Get local time from iPhone [local NSDate]

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

About buildingmyworld

Will fill this part later. Captain procrastinator mode is currently on!
This entry was posted in iOS Development, Objective-c, Uncategorized and tagged , , , , , , , , , , . Bookmark the permalink.

12 Responses to Get local time from iPhone [local NSDate]

  1. lars says:

    Thanks alot!!!

  2. Eliseo says:

    Awesome! Very helpful.

  3. allbemate says:

    Very Helpful, thanks a lot ;))

  4. Anonymous says:

    Thank you sooo much!

  5. appbie says:

    Thank you very much!!

  6. ramesh says:

    Thanks a lot

  7. Anonymous says:

    Thank you, sir!
    Just what i needed.

  8. Anonymous says:

    Hmm, this is technically wrong since NSDate actually represents the number of seconds that have elapsed since 2001-01-01.

  9. Mickey says:

    Thank you very much!

  10. Stephane says:

    Merci beaucoup 🙂

  11. Anonymous says:

    thanks a lot… it helps for me…

Leave a comment