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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With