DateFormatter from “24:00” string returns Nil

前端 未结 1 907
没有蜡笔的小新
没有蜡笔的小新 2021-01-27 10:43

I cannot seem to figure out why only \"24:00\" returns nil instead of 12:00AM, whereas \"23:59\" returns correctly as 11:59PM.

let dateAsString = \"24:00\"
let d         


        
相关标签:
1条回答
  • 2021-01-27 11:01

    You are using the wrong date format for the hour component. For values from 1-24 you have to use k, if you have a leading zero you need to use kk:

    let dateAsString = "24:00"
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "kk:mm"
    if let date = dateFormatter.date(from: dateAsString) {
        dateFormatter.dateFormat = "h:mm a"
        let date2 = dateFormatter.string(from: date)
        print(date2) // "12:00 AM\n"
    }
    
    0 讨论(0)
提交回复
热议问题