问题
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.
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
has settings that let you change aspects of the conversion, like the decimal separator.
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?
回答1:
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)
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
.
来源:https://stackoverflow.com/questions/40425664/can-you-override-nsdateformatter-12-vs-24-hour-time-format-without-using-a-custo