Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 865
Dipen Shah Avatar asked Jan 28 '23 16:01

Dipen Shah


1 Answers

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.

like image 105
vadian Avatar answered Jan 31 '23 22:01

vadian