Convert NSString to NSDate results in NULL
I want to convert the following date: 2010-02-01T13:58:58.513Z
Which is stored in a NSString
to and NSDate
.
The following however just shows "NULL" in the debugger
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-DDTHH:MM:SS.tttZ"];
NSLog(@"Output: %@", [fo开发者_运维技巧rmatter dateFromString:@"2010-02-01T13:58:58.513Z"]);
[formatter release];
Ideas?
You have to escape the "T" in the format string with single quotes.
[formatter setDateFormat:@"YYYY-MM-DD'T'HH:MM:SS.tttZ"];
--
Edit: your formatters aren't completely correct either. ttt for instance is not a valid formatter according to the documentation. Official documentation
If I do this I can get it to work, but that doesn't solve the Z problem:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-DD'T'HH:mm:ss.SSS"];
NSLog(@"Output: %@", [formatter dateFromString:@"2010-02-01T13:58:58.513"]);
[formatter release];
--
Edit 2: Bingo, found the correct formatter.
[formatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss.SSS'Z'"];
Best Guess: Your date format has a space in it. Try this:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-DD'T'HH:mm:SS.SSS'Z'"];
NSDate *date = [formatter dateFromString:@"2010-02-01T13:58:58.513Z"];
NSLog(@"Output: %@", [date description]);
[formatter release];
There are several problem in your format :
- MM is for month while mm is for minutes
- SS does not exists, use ss instead
- same for ttt, use AAA
- there is space between in your format string that looks like a typo but will cause failure
what time zone does Z code stand for at the end of your time (2010-02-01T13:58:58.513Z)
try
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss.AAA'Z'"];
This will create a GMT Time because it recognize the Z ate the end a as simple letter and not as time zone.
Edit : [formatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss.SSS'Z'"]
精彩评论