简体   繁体   中英

NSString to NSDate gives date with a previous day

I'm trying to convert an NSString to NSDate. My incoming string is 02/03/2015 my converting is done like this:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.locale = [NSLocale currentLocale];
dateFormat.timeZone = [NSTimeZone localTimeZone];
dateFormat.timeStyle = NSDateFormatterShortStyle;
dateFormat.dateStyle = NSDateFormatterShortStyle;
dateFormat.locale = [NSLocale currentLocale];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSDate *date = [dateFormat dateFromString:jsonObject[@"chartDate"]];

My ouput is: "2015-03-01 23:00:00 +0000" So suddenly the date is one day back (this is retrieved from Coredata, where it is a NSDate).

Can someone explain me whats wrong?

No, it is one hour back. The reason for this is the time zone:

Unexpected value from NSDate

The output has the timezone "+0000": Likely your computer is set to a timezone "+0100".

What you are getting wrong is not understanding what NSDate means. NSDate contains points in time without a timezone. NSDate is displayed using UTC, that is it displays the time that would be in London without daylight savings time. If you are in New York, then at the start of today (midnight) in New York, the time in London would be 6am, and that's what NSDate displays. If you are in Moscow, then at the start of today (midnight) in Moscow, the time in London would be 10pm of the previous day, and that's what NSDate displays.

There is nothing you can and nothing you should do about this, and it is perfectly correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM