Swift converting NSDate to 24h Format fails on Device

末鹿安然 提交于 2019-11-28 13:13:42

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!