Swift converting NSDate to 24h Format fails on Dev

2019-01-20 07:14发布

问题:

I'm facing an annoying error when i run my application on my iPhone6.
I need to convert an hour (picked by a datePicker) from 12h to 24h format.
Simple thing! Right, I'm pretty sure about that but... my code works on simulator but not on device.
The code is the following:

func convertTimeTo24HoursFomratString() -> String {
        let dateFormatter = NSDateFormatter()
        // isFormatTime24Hours is a static function that returns me if the device has a 24h clock or not. It works fine both on device and on simulator
        //if NSDateUtility.isFormatTime24Hours() {
        //    dateFormatter.dateFormat = "h:mm a"
        //    return dateFormatter.stringFromDate(self)
        //}

        dateFormatter.dateFormat = "HH:mm"
        return dateFormatter.stringFromDate(self)
}

Where am I doing wrong?
iOS version is 9.1 everywhere.
Thanks in advance for any answer!

[EDIT after Paul.s question]
On simulator it returns 24h formatted date (right).
On device it returns 12h formatted date (wrong).

回答1:

QA1480: set yourself to be a a formatter's locale to en_US_POSIX. Otherwise your device's locale will affect date patterns.



回答2:

There's an example from Apple's developer library that might be related to your case.

The representation of the time may be 13:00. In iOS, however, if the user has switched 24-Hour Time to Off, the time may be 1:00 pm.

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1

I would recommend to avoid providing custom formats. Try to use dateStyle and timeStyle if possible. This will ensure adaptivity for all your users.



回答3:

try this

lazy var dateFormatter: NSDateFormatter = {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH mm"
    return dateFormatter
}()

than U can call the function like this

let dateYour = YourTextField.text
date = dateFormatter.dateFromString(dateYour!)!

or

var date : NSDate
let dateYour2 = dateFormatter.stringFromDate(date)

anyway since IOS9 U can pass nil in order ti use international format

var time = time.descriptionWithLocale(nil)
print(time) // 2015-10-30 14:12:18 +0100


回答4:

let date = NSDate()                     // 31 Oct 2015 14:04
let formater = NSDateFormatter.init()
formater.setLocalizedDateFormatFromTemplate("HH:mm")
formater.stringFromDate(date)           // 14:04
formater.setLocalizedDateFormatFromTemplate("hh:mm")
formater.stringFromDate(date)           // 2:12 PM
formater.dateFormat = "HH:mm"
formater.stringFromDate(date)           // 14:04
formater.dateFormat = "hh:mm"
formater.stringFromDate(date)           // 02:04

checked on simulator, checked on device ... so, hard to say ...