Need help for specific date format

2019-09-20 17:04发布

I have next date string,

2011-08-30T11:44:54.345-04:00

Help me to compose right format to parse it with dateFromString:

3条回答
Anthone
2楼-- · 2019-09-20 17:17

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.

查看更多
劫难
3楼-- · 2019-09-20 17:21

http://cocoawithlove.com/2009/05/simple-methods-for-date-formatting-and.html

This link will provide a best date formatting examples.

查看更多
别忘想泡老子
4楼-- · 2019-09-20 17:26

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.

查看更多
登录 后发表回答