Why my NSDate Formatter can't convert correctl

2020-04-22 01:57发布

I have an NSDate Formatter that should create an NSDate from string and should return it formated. The problem is that the result of converting from String to NSDate is wrong, the bigger problem is that on iPhone OS 3.1.2 it returns null while in the simulator it returns a wrong date.

//start formating date
NSMutableString *rawNewsDate = [NSMutableString stringWithString:@"Wed, 3 Feb 2010 14:47:11 CET"];
[rawNewsDate replaceOccurrencesOfString:@" CET" withString:@"" options:0 range:NSMakeRange(0, [rawNewsDate length])];

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEE, d MMM YYYY HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:rawNewsDate]; 
[dateFormat setDateFormat:@"d.M.YYYY | HH:mm"];
NSString *formatedDate = [dateFormat stringFromDate:date];  
NSLog(@"Formated Date %@", formatedDate);
[dateFormat release];

On the simulator in the console, after running the code, the NSDate converted from the string is 2009-12-23 14:47:11 +0200 and the formated one 23.12.2009 | 14:47 .

On the device in the console the NSDate converted from the string is null and the formated also null.

The result should be 03.02.2010 | 14:47.

Any pointers? Thanks

1条回答
等我变得足够好
2楼-- · 2020-04-22 02:23

In the format strings, change YYYY to yyyy (lowercase). See if this fixes the simulator result.

If it's still wrong on the device, is it set to US region? If not, try doing a setLocale on the formatter to en_US.

Here is a reference for date format patterns:
http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns

查看更多
登录 后发表回答