How can I convert "2020-04-10T18:46:42+08:00" to "18:46" in Swift?

49 Views Asked by At

How can I convert "2020-04-10T18:46:42+08:00" to "18:46" in Swift?

I try to format this but I can't find a better solution.

2

There are 2 best solutions below

1
Sarvesh Singh On BEST ANSWER

Calling Function

let getDate = "2020-04-10T18:46:42+08:00"
let x = self.dateInRequiredFormat(stringDate: getDate, requiredFormat : "HH:mm")
print("date:- \(x)")

Function for date formatting

 func dateInRequiredFormat(stringDate:String, requiredFormat:String)->String{
    let dateFormatter = DateFormatter()
    dateFormatter.calendar = Calendar(identifier: .gregorian)
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    let checkInDateStr = dateFormatter.date(from: stringDate)!
    dateFormatter.dateFormat = requiredFormat
    let dateInRequiredFormat = dateFormatter.string(from: checkInDateStr)
    return dateInRequiredFormat
}
0
Parag Bafna On

You can use Calendar class component(_:from:) method to get an hour and minutes.

let calendar = Calendar.current
calendar.component(.hour, from: date) // hour
calendar.component(.minute, from: date) // minute