Obj-C 中将 24 小时转换为 12 小时时间格式
我目前以 24 小时格式显示时间,因为这是我现在利用现有数据做的最简单的事情。
我得到的时间是“自午夜以来的分钟数”,例如,上午 07:00 或 7:00 是“420”,晚上 21:30 或 9:30 是“1290”,依此类推。
[NSString stringWithFormat:@"%02d:%02d - %02d:%02d", (open / 60), (open % 60), (close / 60), (close % 60)]
有没有一种好方法使用 NSDateFormatter 将 24 小时转换为 12 小时?我尝试了很多方法,但我从来没有得到 100% 正确的格式。
我也尝试过使用大量的 if 语句,但最终却得到了太多的代码行,在我看来,对于这样一个相对“简单”的工作来说,这应该是完全没有必要的。
另外,无论我尝试什么,我最终都会在开头没有“1”的情况下得到错误的 12h 格式,例如“09:30 am”等。我可以通过查找后缀来删除它,但这似乎又是这样乏味又奇怪。
I currently display time in 24h format, because it's the easiest thing for me to do right now with the data I have.
I get the time in "minutes since midnight", so for example, 07:00 or 7:00 a.m is "420" and 21:30 or 9:30 p.m is "1290" and so on.
[NSString stringWithFormat:@"%02d:%02d - %02d:%02d", (open / 60), (open % 60), (close / 60), (close % 60)]
Is there a nice way to use NSDateFormatter to convert from 24h to 12h? I have tried a bunch of things, but I never end up with 100% correct formatting.
I have also tried with lots of if statements, only to end up with way too many lines of code, which should be completely unnecessary in my opinion for such a relatively "easy" job.
Also, no matter I try I also end up with wrong 12h formatting for hours without "1" in the beginning, for example "09:30 a.m.", etc. I can strip this by looking for the suffix, but again this just seems to tedious and weird.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您确实应该使用系统的默认日期格式:
或者如果您坚持这样做
You should really use the system's default date formatting:
Or if you insist you can do
对于像我这样的新手,我在日期格式化程序上遇到了困难,发现 [NSCalendar currentCalendar] 将使用用户首选项来设置时区。在我的情况下,我想转换服务器给我的时间,所以它总是错误的。我在我的例子中使用了这个简单的函数。
For someone new like me I struggled with the date formatter and found that the [NSCalendar currentCalendar] will use the users preferences to set timezone. In my situation I wanted to convert a time that a server gave me so it was always wrong. I used this simple function in my case.
你可以试试这个。它对我有用
You can try this.It works for me
检查您的分钟数是否小于 720(12 小时),如果是,则为 AM,如果不是 PM(因此您需要花费 -12 小时才能从军事时间变为 12 小时),然后根据需要添加后缀。它并不漂亮,但它是一个相对简单的格式化工作。
check if your minutes are less than 720 (12 hours), if so its AM, if not its PM (so you would do hours -12 to get from military to 12h) then add the suffix as needed. Its not pretty, but its a relatively simple formatting job.