Dateformatter gives wrong time on conversation [duplicate]

安稳与你 提交于 2019-11-28 13:09:36

- [NSDate description] (which is called when passing it to NSLog) always prints the date object in GMT timezone, not your local timezone. If you want an accurate string representation of the date, use a date formatter to create a correct string according to your timezone.

milanpanchal

As @Leo Natan said, - [NSDate description] always gives date in GMT timezone. If you want to convert into local timezone then use following code.

NSString *dateStr = @"2013-12-20 12:10:40";

// Convert string to date object
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
NSDate *lastUpdatedate = [dateFormatter dateFromString:dateStr];

NSLog(@"lastUpdatedate : %@",[self getLocalTime:lastUpdatedate]);



-(NSDate *) getLocalTime:(NSDate *)date {
    NSTimeZone *tz = [NSTimeZone defaultTimeZone];
    NSInteger seconds = [tz secondsFromGMTForDate: date];
    return [NSDate dateWithTimeInterval: seconds sinceDate: date];
}

OUTPUT:

lastUpdatedate : 2013-12-20 12:10:40 +0000

NSString *dateStr = @"2013-12-20 12:10:40";
NSDateFormatter *dateFormatterTest = [[NSDateFormatter alloc] init];
[dateFormatterTest setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
[dateFormatterTest setLocale:[NSLocale currentLocale]];
NSDate *d = [dateFormatterTest dateFromString:dateStr];

Set NSLocale in your code, and you get perfect result.

You can try this:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

NSDate *lastUpdatedate = [dateFormatter dateFromString:dateStr];

NSTimeInterval sourceGMTOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:lastUpdatedate];

lastUpdatedate = [lastUpdatedate dateByAddingTimeInterval:sourceGMTOffset];

NSLog(@"lastUpdatedate : %@",lastUpdatedate);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!