-3

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.

Cœur
  • 34,719
  • 24
  • 185
  • 251
Mr Ice
  • 690
  • 1
  • 5
  • 9

2 Answers2

1

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
Parag Bafna
  • 22,567
  • 8
  • 67
  • 140
1

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
}