Search code examples
swiftdateswift4.1

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


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.


Solution

  • 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
    }