Convert NSString to NSDate with new format

2019-01-29 06:48发布

This question was asked a lot, but I can't find the solution for my problem.

What I want: Convert a date given as a NSString into a NSDate with a complete different format. I want to convert Tue, 31 Jul 2012 10:15:00 GMT to 2012-07-31 10:15:00 +0000.

My code:

NSString *startDateString = @"Tue, 31 Jul 2012 10:15:00 GMT"; //in real from a server

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss"];

NSDate *startDate = [formatter dateFromString:startDateString];
[formatter setDateFormat:@"yyy-MM-dd HH:mm:ss'Z'"];

NSString *endDateString = [formatter stringFromDate:startDate];
NSDate *endDate = [formatter dateFromString:endDateString];

Problem: endDate is nil.

Edit:
Found a strange behaviour.
When I change the first dateFormat to @"EEE, dd MMM yyy HH:mm:ss 'GMT'" (added GMT) then the output of endDate is correct, but only in the Simulator. On the device it is still nil.
With the dateFormat without "GMT" the value is nil on the Simulator and on the Device.

2条回答
一纸荒年 Trace。
2楼-- · 2019-01-29 07:40

this is working well for me, you might use it:

NSString *startDateString = @"Tue, 31 Jul 2012 10:15:00 GMT"; //in real from a server

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ssZZZ"]; // SPOT the difference in this line

NSDate *startDate = [formatter dateFromString:startDateString];
[formatter setDateFormat:@"yyy-MM-dd HH:mm:ssZZZ"]; // and SPOT the difference in this line

NSString *endDateString = [formatter stringFromDate:startDate];
NSDate *endDate = [formatter dateFromString:endDateString];

NSLog(@"%@", endDate);

the endDate is:

2012-07-31 10:15:00 +0000

UPDATE #1

it has been tested on the real device only!

查看更多
够拽才男人
3楼-- · 2019-01-29 07:48

Add the following before converting

[formatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"]];
查看更多
登录 后发表回答