Dateformatter gives wrong time on conversation [duplicate]

只谈情不闲聊 提交于 2019-11-27 07:30:29

问题


This question already has an answer here:

  • NSDate Format outputting wrong date 5 answers
  • Getting date from [NSDate date] off by a few hours 3 answers

I am trying to convert my date string to NSDate but its return correct date and wrong time.

This is my 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 : %@",lastUpdatedate);

It returns this :

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

回答1:


- [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.




回答2:


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




回答3:


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.




回答4:


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);


来源:https://stackoverflow.com/questions/20738102/dateformatter-gives-wrong-time-on-conversation

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