将时间转换为 12 小时格式

发布于 2024-10-06 23:09:42 字数 66 浏览 0 评论 0原文

请告诉我如何将时间转换为 12 小时格式..
我有一个已转换为日期的字符串,但它是 24 小时格式......

Please tell me how to convert time to 12 hr format..
I have a string which i have converted to date but it is in 24 hr format....

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

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

发布评论

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

评论(4

相思碎 2024-10-13 23:09:42

您可以使用 24 小时时钟格式而不是 12 小时格式。因此,请使用格式字符串中带有 H 的 NSDateFormatter。使用其中一种预定义格式最终将使用您的系统本地化,这可能是 12 小时格式。

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"HH:mm"];

这里使用正则表达式提出了另一个解决方案:
24小时到12小时时间转换,将字符插入字符串

You could use the 24 hour clock format instead of the 12 hour format. So use a NSDateFormatter with H in the format string. Using one of the predefined formats will end up using your systems localization which probably is the 12 hour format.

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"HH:mm"];

another solution is presented here using regex:
24hr to 12hr time convert, insert character to string

茶底世界 2024-10-13 23:09:42

考虑到你有一个名为 time 的小时...

if (time>12)
时间=时间-12;

considering you have an hour int named time...

if (time>12)
time=time-12;

孤独陪着我 2024-10-13 23:09:42

当你说你已经将其转换为日期时,你的意思是什么?您的意思是您将其放在 NSDate 对象中吗?如果是这样,则日期不是采用 24 小时日期格式。 NSDate 并不关心日期在屏幕上的显示效果。

格式来自您的本地化设置。事情应该是这样的。我不想要 12 小时格式的时间,就像你不想要 24 小时格式的时间一样。

但要直接回答这个问题,如果您想覆盖默认值,您可能必须编写自己的格式化代码。当我从第三方数据源接收日期时,我必须这样做才能解决 NSDateFormatter 中的错误。

When you say you've converted it to a date, what do you mean? Do you mean you have it in an NSDate object? If so, the date is not in 24hr date format. NSDate does not concern itself with how the date will look on-screen.

The formatting comes from your localisation settings. Which is how it should be. I don't want times in 12hr format any more than you want them in 24hr.

But to directly answer the question, you may have to write your own formatting code if you want to override the defaults. I had to do this to work around bugs in NSDateFormatter when I received dates from a third party data source.

我乃一代侩神 2024-10-13 23:09:42

要将日期格式从 12 小时更改为 24 小时或从 24 小时更改为 12 小时,只需将 hh:mm 更改为 HH:mm 格式,其中 h 代表 12 小时,H 代表 24 小时。
请记住更改您的位置。

NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"HH:mm"];

To change the date format from 12 to 24 hours or from 24 to 12 simply change hh:mm to HH:mm format where h is for 12 hours and H is for 24 hours.
Remember to change your location.

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