0

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 ~

3 Answers3

0

Time format 24 hours to 12 hours

let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"

let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print("12 hour formatted Date:",Date12) // 1:15 PM
Nikunj Kumbhani
  • 3,758
  • 2
  • 26
  • 51
0

You can try this, but please know that you will not have the todays date since you've only set the hour/minute, it doesn't know what year, month or day you want.

let dateString = "20:32"
let df = DateFormatter()
df.dateFormat = "HH:mm"
let d = df.date(from: dateString) // "Jan 1, 2000 at 8:32 PM"
Marius Fanu
  • 6,589
  • 1
  • 17
  • 19
0

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

AtulParmar
  • 4,358
  • 1
  • 24
  • 45