Home > Enterprise >  How to format date from 12h to 24h in SwiftUI?
How to format date from 12h to 24h in SwiftUI?

Time:02-03

I am trying to format a 12h date to 24h date, but is not working, maybe I am doing something wrong. I'll share the code below so maybe you can help me.

"syncViewModel._order.deliveryDate" is the date that I am getting from the backend and is a string.

 Text(dateFormatTime(date: syncViewModel._order.deliveryDate ?? ""), style: .time)
  func dateFormatTime(date : String) -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = .current
        dateFormatter.locale = NSLocale(localeIdentifier: "en_GB") as Locale
        return dateFormatter.date(from: date) ?? Date.now
    }

This is the format of my date : 2022-01-25T17:00:00 enter image description here

CodePudding user response:

You use a date formatter to convert a date string to a Date. You can then use an additional date formatter, to directly return the time in the format that you want, as a string:

func timeIn24HourFormat(from date: Date) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm"
    return dateFormatter.string(from: date)
}

That way you can use it in SwiftUI directly, without requesting the time style:

Text(timeIn24HourFormat(from: dateFormatTime(date: "2021-07-14T17:00:00")))

CodePudding user response:

I tried to run my code on a real Device and it works, it shows me the 24h format, maybe the simulator run on 12h format.

  •  Tags:  
  • Related