如何更改日期/时间的格式?
我有这个日期和时间格式:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你的格式化字符串有问题。您应该仅使用在 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 attt
- 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".你把事情搞倒了。如果这是要向用户显示的日期/时间,您需要按照用户想要的方式呈现,而不是您想要的方式。例如,美国以外的大多数人都会对 MM-dd-yyyy 感到困惑,特别是当日期小于 13 时。考虑使用 -setDateStyle: 和 -setTimeStyle :。这样,显示字符串就会按照用户的预期显示出来。
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.