Need help for specific date format

梦想的初衷 提交于 2019-12-13 08:59:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!