mangesh
mangesh

Reputation: 574

Time conversion in swift in different format

I want to convert the time string from 15:00:00 AM to 03:00 PM, this is what I am trying to achieve the results.

var str  = "15:00:00 AM"          //  "15:00:00 AM" 

let df = DateFormatter()
df.timeZone = TimeZone.current
df.dateFormat = "HH:mm:ss a"    // "Jan 1, 2000, 12:00 AM"
let date = df.date(from: str)

let df1 = DateFormatter()
df1.dateFormat = "hh:mm a"
str = df1.string(from: date!)   // "12:00 AM"

Not sure where I am missing tried different approaches but still I am not able to convert the times correctly.

PS: More of the answer, I am checking for the possibility of the conversion, as the time string I am getting is from server end and I can update them for correction.

Upvotes: 0

Views: 363

Answers (1)

ali hassoun
ali hassoun

Reputation: 161

Good Morning , please try this code

let now = NSDate()
let df = DateFormatter()
df.dateFormat = "hh:mm a"
let result = df.string(from: now as Date)

Upvotes: 1

Related Questions