使用 NSDateFormatter 格式化日期时出现问题

发布于 2024-12-03 23:34:34 字数 601 浏览 1 评论 0原文

我有以下日期:

2011-09-09T18:01:47Z

我希望它显示为

“9/9/11 at 1:47PM” 无论正确的时间是什么

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江湖正好 2024-12-10 23:34:34

两者的格式相同,它们与您的输入和输出几乎没有关系。遇到问题时,请参阅 Unicode 数据格式模式

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文