您可以在不使用自定义 dateFormat 的情况下覆盖 NSDateFormatter 12 与 24 小时时间格式吗 [英] Can you override NSDateFormatter 12 vs 24 hour time format without using a custom dateFormat

查看:45
本文介绍了您可以在不使用自定义 dateFormat 的情况下覆盖 NSDateFormatter 12 与 24 小时时间格式吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将日期转换为用户时区中的显示字符串,但我想使用 24 小时时间格式而不是 12 小时时间格式.

I want to convert a Date as a display string in the user's time zone, but I want to use 24 hour time format rather than 12 hour time format.

我知道我可以通过显式设置自定义 dateFormat 字符串来做到这一点,但这失去了让系统生成符合用户区域设置的字符串的好处.

I know I can do that by explicitly setting a custom dateFormat string, but that loses the benefit of letting the system generate strings that conform to the user's locale setting.

NSNumberFormatter 有一些设置可以让你改变转换的各个方面,比如小数点分隔符.

NSNumberFormatter has settings that let you change aspects of the conversion, like the decimal separator.

NSDateFormatter 是否有设置可以让我在 12 和 24 小时格式之间切换,而不必求助于完全自定义的格式?

Is there a setting for NSDateFormatter that will let me switch between 12 and 24 hour format without having to resort to a completely custom format?

推荐答案

DateFormatter 具有 dateFormat(fromTemplate:options:locale:) 方法.使用它可以根据用户的区域设置获得正确的 24 小时格式.

DateFormatter has the dateFormat(fromTemplate:options:locale:) method. Use this to get a proper 24-hour format based on the user's locale.

let fmt = DateFormatter.dateFormat(fromTemplate: "Hms", options: 0, locale: Locale.current)

尽管对于大多数语言环境这似乎返回 HH:mm:ss.739 个可用语言环境中只有 85 个返回HH:mm:ss 以外的内容.

Though this seems to return HH:mm:ss for most locales. Only 85 of the 739 available locales return something other than HH:mm:ss.

这篇关于您可以在不使用自定义 dateFormat 的情况下覆盖 NSDateFormatter 12 与 24 小时时间格式吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆