Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift how to get 12 hours format if system is 24 hour format [duplicate]

Tags:

ios

swift

My iPhone device system was set in 24hours format i want to get 12 hours format, that is: 23:27 get 11:27 PM.

I tried:

            let today = NSDate()
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "hh:mm a"
            let string = dateFormatter.string(from: today as Date) // 23:27

got 23:27 string.

I found this: How to get 12 hour format time string when system is set to use 24 hour format

            let today = NSDate()
            let dateFormatter = DateFormatter()
            let dateFormat = DateFormatter.dateFormat(fromTemplate:"hh:mm a", options: 0, locale: NSLocale.current)
            dateFormatter.dateFormat = dateFormat
            let string = dateFormatter.string(from: today as Date) //23:27 i want 11:27 pm

But it doesn't work i still got 23:27 string not 11:27pm string.

Thanks!

EDIT: According to shallowThought's answer not sure if Locale is the case?

enter image description here

EDIT2 Add this:

dateFormatter1.locale = Locale(identifier: "en_US_POSIX")

works. And my current locale is en_CN.

like image 578
William Hu Avatar asked Oct 18 '22 21:10

William Hu


1 Answers

Your code works fine here on an iPhone6, iOS 10.1.1 with date set to 24 hours:

override func viewDidLoad() {
    super.viewDidLoad()

    let today = NSDate()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm a"
    let string = dateFormatter.string(from: today as Date)
    print(string)
}

Prints:

04:38 PM
like image 193
shallowThought Avatar answered Nov 04 '22 01:11

shallowThought