简体   繁体   中英

Convert NSString to NSDate is not working

i use code same this best answer

Converting NSString to NSDate (and back again)

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];

but dateFromString result is 2010-01-31 17:00:00 +0000 why it not same day.
i cannot compare date.

这是因为你当前的时区,添加这个然后它会给你正确的日期

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

Add the following line right after where you have set the date format. It because it will convert by default with local timezone of the device. It works for me!

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

It is actually the same date. But the date formatter, by default, parses the date string in the local timezone of the device if a timezone is not passed in. In your case, your date was intepreted as Midnight February 2nd 2010 UTC+7 which is January 31st 2010 17:00 UTC.

If the date string is always in UTC, pass in the UTC timezone into the date formatter like this:

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];

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