Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

ios - Swift converting NSDate to 24h Format fails on Device

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...