Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert GMT NSDate to device's current Time Zone

I'm using Parse.com to store some values:

enter image description here

These are GMT values. How do I convert these to the device's current time zone and get NSDate as a result?

like image 202
Oscar Swanros Avatar asked Aug 07 '13 15:08

Oscar Swanros


3 Answers

NSDate is always represented in GMT. It's just how you represent it that may change.

If you want to print the date to label.text, then convert it to a string using NSDateFormatter and [NSTimeZone localTimeZone], as follows:

NSString *gmtDateString = @"08/12/2013 21:01";

NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"dd/MM/yyyy HH:mm"];

//Create the date assuming the given string is in GMT
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *date = [df dateFromString:gmtDateString];

//Create a date string in the local timezone
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];
NSString *localDateString = [df stringFromDate:date];
NSLog(@"date = %@", localDateString);

// My local timezone is: Europe/London (GMT+01:00) offset 3600 (Daylight)
// prints out: date = 08/12/2013 22:01
like image 190
Sam Avatar answered Nov 02 '22 16:11

Sam


The easiest method I've found is this:

NSDate *someDateInUTC = …;
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];
like image 25
Sendoa Avatar answered Nov 02 '22 16:11

Sendoa


This is a very clean way to change the NSDate to a local time zone date

extension NSDate {

    func toLocalTime() -> NSDate {

        let timeZone = NSTimeZone.local

        let seconds : TimeInterval = Double(timeZone.secondsFromGMT(for:self as Date))

        let localDate = NSDate(timeInterval: seconds, since: self as Date)
        return localDate
    }
}

taken from https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/

like image 5
Maria Avatar answered Nov 02 '22 17:11

Maria