Swift - DateFormat HH:mm的坑

2023/08/24閱讀時間約 3 分鐘

一般來說在swift把Date轉成String,會使用dateFormat轉換

extension Date {
func string(withFormat format: String = "dd/MM/yyyy HH:mm") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}

大寫的HH:mm是24小時制,小寫的hh:mm是12小時制

let date = Date()
print(date.string(withFormat: "yyyy/MM/dd HH:mm")) // 2023/08/24 16:21
print(date.string(withFormat: "yyyy/MM/dd hh:mm")) // 2023/08/24 04:21

但用HH:mm,碰到一個使用者回報,他的時間顯示是

2023/08/24 下午 04:21(哪來的下午啊?????

用了很多方法,用該使用者的iOS版本測、調手機時間調時區、調地區、調12小時、24小時制都無法重現情境,找了很久總算找到這篇 https://www.jianshu.com/p/79465eb4e4c4

要固定輸出的格式,Locale需指定en_US_POSIX

extension Date {
func toString(withFormat format: String = "dd/MM/yyyy HH:mm") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.calendar = Calendar(identifier: .gregorian)
return dateFormatter.string(from: self)
}
}

官方解釋

if you’re working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is “en_US_POSIX”, a locale that’s specifically designed to yield US English results regardless of both user and system preferences.

https://developer.apple.com/library/archive/qa/qa1480/_index.html

另外跟版本應該無關,因為這篇是iOS15.4,但我們的使用者是16.5.1,目前不知道規律但貌似中國的iphone比較有機會碰到

大蘋果:沒有遵守開發規範是你自己活該(指

5會員
22內容數
紀錄iOS開發上遇到的問題或是一些流程筆記。主要都是Swift。
留言0
查看全部
發表第一個留言支持創作者!
從 Google News 追蹤更多 vocus 的最新精選內容