如何更改日期/时间的格式?

发布于 2024-09-02 22:50:27 字数 545 浏览 1 评论 0原文

我有这个日期和时间格式:

2010-05-19 07:53:30

并且想将其更改为:

Wednesday @ 7:53PM 5/19/2010

我正在这样做,它获取当前格式:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

但是当我更改格式时,我最终得到一个空值。例如:

formatter.dateFormat = @"hh:mm tt MM-dd-yyyy";
date = [formatter stringFromDate:formattedDate];

日期将为空。我想将最终结果放入 NSString 中。如果时间和日期可以作为单独的属性出现,那就太好了,这样我就可以按照我喜欢的方式安排它们。关于如何更改格式有什么想法吗?

I have this date and time format:

2010-05-19 07:53:30

and would like to change it to:

Wednesday @ 7:53PM 5/19/2010

I'm doing this, which gets the current format:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

but when I change the format, I end up with a null. For example:

formatter.dateFormat = @"hh:mm tt MM-dd-yyyy";
date = [formatter stringFromDate:formattedDate];

date will be null. I want to put the end result into an NSString. It would be nice if time and date could come out as separate properties so I can arrange them however I like. Any ideas on how I can change the formatting?

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

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

发布评论

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

评论(2

猫弦 2024-09-09 22:50:27

我认为你的格式化字符串有问题。您应该仅使用在 UTS#35 日期格式模式中的表中找到的字符。我尝试了您的代码,虽然时间 hh:mm 显示正确,但格式在 tt 处停止 - 不在表中!

如果您确实想要格式字符串中没有表中的字符,您可以转义它们,例如 hh 'o''clock' a, zzzz - 生成类似“12 o'clock PM, Pacific”的格式夏令时”。

I think your formatting string is the problem. You should only use the characters you find in the table in UTS#35 Date Format Patterns. I tried your code and while the time hh:mm displays correctly, formatting stops at tt - not in the table!

If you really want characters in the format string that are not in the table you can escape them, like hh 'o''clock' a, zzzz - produces format like "12 o'clock PM, Pacific Daylight Time".

谁许谁一生繁华 2024-09-09 22:50:27

如果时间和日期可以作为单独的属性出现,那就太好了,这样我就可以按照我喜欢的方式安排它们。关于如何更改格式有什么想法吗?

你把事情搞倒了。如果这是要向用户显示的日期/时间,您需要按照用户想要的方式呈现,而不是您想要的方式。例如,美国以外的大多数人都会对 MM-dd-yyyy 感到困惑,特别是当日期小于 13 时。考虑使用 -setDateStyle:-setTimeStyle :。这样,显示字符串就会按照用户的预期显示出来。

It would be nice if time and date could come out as separate properties so I can arrange them however I like. Any ideas on how I can change the formatting?

You have things backwards. If this is a date/time to be displayed to the user, you need to present it how the user wants it, not how you want it. For instance, most people outside the USA will be confused by MM-dd-yyyy particularly if the day is less than 13. Consider using -setDateStyle: and -setTimeStyle:. That way, the display string will come out as the user expects.

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