问题
I have next date string,
2011-08-30T11:44:54.345-04:00
Help me to compose right format to parse it with dateFromString:
回答1:
You need to eliminate the last colon (timezone, "-04:00" -> "-0400"), as Z
will take something like "-0800", then you can give this a try:
NSString *dateString = @"2011-08-30T11:44:54.345-04:00";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-ddEHH:mm:ss.SSSZ"];
NSDate *date = [dateFormat dateFromString:dateString];
[dateFormat release];
For more information on date formatting, refer to this page.
回答2:
This is following the tilo's answer but with few things added.
NSString *dateString = @"2011-08-30T11:44:54.345-04:00";
NSRange range = [dateString rangeOfString:@":" options:NSBackwardsSearch];
dateString = [dateString stringByReplacingOccurrencesOfString:@":" withString:@"" options:0 range:range];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-ddEHH:mm:ss.SSSZ"];
NSDate *date = [dateFormat dateFromString:dateString];
[dateFormat release];
You would get the required format.
来源:https://stackoverflow.com/questions/7873690/need-help-for-specific-date-format