I have a time string only "17:10:51.2800000" want to change in HH:mm, but unable to convert it. I follow this code:
let date = self.convertStringToDate(getDate: time!)
let dateString = self.convertDateToString(getDate: date)
func convertDateToString(getDate: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSSS"
formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
let myString = formatter.string(from: getDate)
let yourDate = formatter.date(from: myString)
formatter.dateFormat = "HH:mm"
formatter.timeZone = TimeZone.current
let dateInString = formatter.string(from: yourDate!)
return dateInString
}
func convertStringToDate(getDate: String) -> Date {
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("HH:mm:ss.SSS")
let dateInString = formatter.date(from: getDate)
formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?//NSTimeZone(name: "UTC") as TimeZone?
////////here dateInString is coming nil while debugging
return dateInString! //?? Date()
}
While debugging convertStringToDate showing nil, but not crashing. I am confused it is correct or not.The time is coming correct after changing to string but not conform my code is correct or not.