Search code examples
iosswiftiphonensdatexcode10.1

not able to convert string to date


I have an string say , "24:00". I need to convert to date.I tried all the ways.But always getting nil.

here is my code :

let timeformat = DateFormatter()
timeformat.dateFormat = "K:mm"
timeformat.locale = Locale(identifier: "en_US_POSIX")
guard let endtime = dateFormatter.date(from: selCloseTime!) else {
                fatalError("ERROR: Date conversion failed due to mismatched format.")
            }

error: Fatal error: ERROR: Date conversion failed due to mismatched format.

i tried changing format to :

HH:mm
H:mm
KK:mm (small & caps  -> k)
K:mm (small & caps - > k)

but always getting nil. My string can be anything like :

"24.00", "01:00", "20:00" , "03:00"

Any help on that .

Thanks in advance ~


Solution

  • Change timeformat.dateFormat = "K:mm" to timeformat.dateFormat = "kk:mm" and see this output.

    let selCloseTime = "20:00"
    let timeformat = DateFormatter()
    timeformat.dateFormat = "kk:mm"
    timeformat.locale = Locale(identifier: "en_US_POSIX")
    guard let endtime = timeformat.date(from: selCloseTime) else {
        fatalError("ERROR: Date conversion failed due to mismatched format.")
    }
    print(endtime)
    

    enter image description here