简体   繁体   中英

NSString to NSDate returns wrong date

I try to convert my NSString to NSDate object, but NSDateFormatter returns me a strange value.

Here is code:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"]; 
NSDate *date = [dateFormat dateFromString:@"2012-08-15 00:00"];
[dateFormat release];

date value is 2012-08-14 21:00 +0000 . It is 3 hours difference between NSString value and NSDate value. I think I've missed something, but I don't know what.

This is what i use:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"]; 

NSDate *date = [dateFormat dateFromString:@"2012-08-15 00:00:00 +0000"];
NSLog(@"\n\n  DATE: %@ \n\n\n", date);

The +0000 is timezone, so make sure you use your timezone, like +0400 .

Edit: If you can't change the string, you can use this code to do it:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"]; 
[dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate *date = [dateFormat dateFromString:@"2012-08-15 00:00"];

我知道NSDate拥有格林威治时间,所以如果您在莫斯科时区,一切都会很好

In objective c for NSDate if you did not set the setTimeZone, NSDate will take default timezone as localTimeZone. so if you need to get the exact date which you give as NSString string format, you need to setTimeZone as UTC. Follow the sample code, I guess it will be helpful for you.

NSDateFormatter *loacalformatter=[[NSDateFormatter alloc]init];
[loacalformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *localDate =[loacalformatter dateFromString:@"2012-08-15 00:00"];
NSLog(@"localDate :%@",localDate);


NSDateFormatter *UTCformatter=[[NSDateFormatter alloc]init];
[UTCformatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[UTCformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *UTCDate =[UTCformatter dateFromString:@"2012-08-15 00:00"];
NSLog(@"UTCDate :%@",UTCDate);
UTCDate :2012-08-15 00:00 +0000 (GMT+00:00)

As suggested in the comments, if the date you receive is UTC then you need to convert it to your local timezone. Apple recommend you always use a properly configured NSDateFormatter when displaying dates, to handle localisation issues.

Here's some example code for turning an NSDate into an NSString:

NSDate *date = // initialised elsewhere

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.locale = [NSLocale currentLocale];
dateFormat.timeZone = [NSTimeZone localTimeZone];
dateFormat.timeStyle = NSDateFormatterShortStyle;
dateFormat.dateStyle = NSDateFormatterShortStyle;    
dateFormat.locale = [NSLocale currentLocale];
NSString *dateAsString = [dateFormat stringFromDate:date];

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