Dateformatter gives wrong time on conversation [du

2019-01-20 07:18发布

问题:

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