5

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.

Community
  • 1
  • 1
William Hu
  • 15,423
  • 11
  • 100
  • 121

1 Answers1

4

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
shallowThought
  • 19,212
  • 9
  • 65
  • 112