1

I want to get the time in 12h or 24h format from DateFormatter according to option "24-Hour-Time" in User Preferences.

If I set "24-Hour-Time" = "on" and DateFormatter like this:

    let formatter = DateFormatter()
    let locale = Locale(identifier: "en_US")
    print(locale)                            // "en_US (fixed)\n"
    formatter.locale = locale 
    formatter.dateStyle = .none
    formatter.timeStyle = .short

    formatter.string(from: Date()) // "2:54 PM" (not "14:54")

But if I set:

    let locale = Locale.current   // "en_US (current)\n"

instead of

    let locale = Locale(identifier: "en_US") // "en_US (fixed)\n"

the result will be

formatter.string(from: Date()) // "14:54"

How to create custom locale setting 12 or 24 hour format.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Igor Kasuan
  • 792
  • 2
  • 10
  • 25
  • I don't know what you are trying to achieve but you can check the user's 24h setting and set a custom dateFormat based on it. `extension DateFormatter { var is24h: Bool { return DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: .current)?.contains("a") == false } }` – Leo Dabus Aug 21 '18 at 14:17

1 Answers1

-1

//MARK:- use this to convert 24 hours time format to 12 hour Formate String

 func TwelveHourFormateFrom24Hours(time : String)->String
    {
        let Time = time.components(separatedBy: ".")
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "H:mm:ss"

        if let inDate = dateFormatter.date(from: Time[0])
        {
            dateFormatter.dateFormat = "h:mm a"
            dateFormatter.timeZone = TimeZone.current
            let outTime = dateFormatter.string(from: inDate)
            print("in \(time)")
            print("out \(outTime)")
            return outTime
        }
        return time
    }

//MARK:- 24 hour Formate String

 func TwentyFourHourFormate(time : String)->String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "h:mm a"

        if let inDate = dateFormatter.date(from: time)
        {
            dateFormatter.dateFormat = "H:mm:ss.sss"
            let outTime = dateFormatter.string(from: inDate)
            print("in \(time)")
            print("out \(outTime)")
            return outTime
        }
        return time
    }
nimesh surani
  • 177
  • 1
  • 13