Problem formatting date using NSDateFormatter

我只是一个虾纸丫 提交于 2019-12-23 07:03:23

问题


I have the following date:

2011-09-09T18:01:47Z

I want it to appear as

"9/9/11 at 1:47PM" whatever the correct time is

This code returns a null string:

NSLog(@"TIME: %@",[message valueForKey:@"created_at"]);
    NSString* time = [message valueForKey:@"created_at"];
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM-dd-yy at HH:mm:ss"];
    NSDate* newTime = [dateFormatter dateFromString:time];
    [dateFormatter setDateFormat:@"MM-dd-yy at HH:mm:ss"];
    NSString* finalTime = [dateFormatter stringFromDate:newTime];

回答1:


Your formatting is the same for both and they have little to no relation to your input and your output. Refer to the Unicode Data Format Patterns whenever you have issues.

NSString *datein = @"2011-09-09T18:01:47Z";

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
//The Z at the end of your string represents Zulu which is UTC
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate* newTime = [dateFormatter dateFromString:datein];

//Add the following line to display the time in the local time zone
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setDateFormat:@"M/d/yy 'at' h:mma"];
NSString* finalTime = [dateFormatter stringFromDate:newTime];
NSLog(@"%@", finalTime);


来源:https://stackoverflow.com/questions/7365817/problem-formatting-date-using-nsdateformatter

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