DateFormatter “HH” not giving time in 24 hour format in swift [duplicate]

。_饼干妹妹 提交于 2019-12-13 02:57:23

问题


I am trying to fetch the currentTime in a 24 hour format with UTC timezone. When I have debugged my app in different devices, I came across a strange problem.

The code works perfectly fine in my device, however it gives time in 12 hour format in my cousin's iPhone having iOS 11.2. So I have tried running app in another device which is iPhone X with same os.

I am not sure what went wrong but then I tried this in few other devices as well and the app runs fine in all other devices. P.S. Older version of my app runs fine in cousin's phone too with the same code.

here is my code which I have used to get currentTime.

        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
        dateFormatter.dateFormat = "EEEE"
        dayOfWeekString = dateFormatter.string(from: NSDate() as Date)

        dateFormatter.dateFormat = "HH"
        let CurrentTime = dateFormatter.string(from: NSDate() as Date)
        let CHour = Int(CurrentTime)!

Looking for the solution


回答1:


DateFormatter considers also the current locale.

It's recommended to set the locale to a fixed value

let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")!
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "HH"
let currentTime = dateFormatter.string(from: Date())

However there is a more reliable way using Calendar. The hour date component is in 24 hour mode anyway and you don't need the conversion to Int

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(abbreviation: "UTC")!
let currentHour = calendar.component(.hour, from: Date())

Note: Don't use NSDate, NSLocale, NSTimeZone etc. in Swift. Use the native structs.



来源:https://stackoverflow.com/questions/48753507/dateformatter-hh-not-giving-time-in-24-hour-format-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!