问题格式化日期使用NSDateFormatter [英] Problem formatting date using NSDateFormatter

查看:79
本文介绍了问题格式化日期使用NSDateFormatter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下日期:

2011-09-09T18:01:47Z

我想让它显示为

9 / 9/11 at 1:47 PM任何正确的时间

此代码返回一个空字符串:

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];


推荐答案

与您的输入和输出无关。每当遇到问题时,请参阅 Unicode数据格式模式

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);

这篇关于问题格式化日期使用NSDateFormatter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆