-3

在我的 iOS 应用程序中,我试图将字符串格式的日期转换为 NSDate。我首先将字符串以正确的格式放入,但在将其更改为 NSDate 时,我得到了不同的输出日期。在下面的代码中,我放置了两个 NSLog,它们显示字符串与日期格式匹配,所以我不知道为什么输出不同。

NSString * list = @"Sun, 24 Mar 2013 21:08:02 +0000";
NSArray *listItems = [list componentsSeparatedByString:@", "];
//24 Mar 2013 21:08:02 +0000

NSArray *listItems1 = [[listItems objectAtIndex:1] componentsSeparatedByString:@" "];
NSString *timeSubString = [[listItems1 objectAtIndex:3] substringWithRange:NSMakeRange(0,5)];
NSString * newConcat = [NSString stringWithFormat:@"%@-%@-%@ %@",[listItems1 objectAtIndex:0],[listItems1 objectAtIndex:1],[listItems1 objectAtIndex:2], timeSubString];
NSLog(@"***DATE STRING***: %@",newConcat);
//***DATE STRING***: 24-Mar-2013 21:08

NSDateFormatter* fmt = [NSDateFormatter new];
[fmt setDateFormat:@"dd-MMM-YYYY HH:mm"];
NSDate* date = [fmt dateFromString:newConcat];
NSLog(@"***OUTPUT DATE***: %@",date);
//***OUTPUT DATE***: 2013-01-06 02:08:00 +0000
NSLog(@"***DATE STRING***: %@", [fmt stringFromDate:date]);
//***DATE STRING***: 05-Jan-2013 21:08
4

1 回答 1

2

你可以这样做

NSString *dateString = @"Sun, 24 Mar 2013 21:08:02 +0000";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];

NSDate *date = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm"];

NSString *newDateString = [dateFormatter stringFromDate:date];
于 2013-03-27T19:28:51.947 回答