1
votes

I'm try to get local time from device

nsdate will return the UTC time

when I convert with localtime zone the string will return current local time...

again I try to convert string to local date but it will return only UTC time

This is my code... how can I get Local time in NSDate...

NSDate *currentDate = [NSDate date];

NSLog(@"currentDate: %@", currentDate); // Result: currentDate: 2014-05-19 05:21:50 +0000

 NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter2 setDateFormat:@"yyyy/MM/dd HH:mm:ss"];

NSString *strDate = [dateFormatter2 stringFromDate:currentDate];

NSLog(@"strDate: %@", strDate); // Result: strDate: 2014/05/19 10:51:50

NSDate *newDate = [dateFormatter2 dateFromString:strDate];

NSLog(@"newDate: %@", newDate); // Result: newDate: 2014-05-19 05:21:50 +0000

can any one help to get local datetime in NSDate

2
OP states: "when I convert with localtime zone the string will return current local time" so there is no problem. - zaph

2 Answers

3
votes

Try this:

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

The time is always saved in NSDate as UTC, that can not be changed.

One can get a string representation for the local timezone, the OP has done that.

NSDate has a reference date of "the first instance of 1 January 2001, GMT"