Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...