如何在Swift中将“ 2020-04-10T18:46:42 + 08:00”转换为“ 18:46”?
我尝试格式化此格式,但找不到更好的解决方案。
答案 0 :(得分:1)
您可以使用Calendar
类component(_:from:)
方法获得一个小时和几分钟。
let calendar = Calendar.current
calendar.component(.hour, from: date) // hour
calendar.component(.minute, from: date) // minute
答案 1 :(得分:1)
呼叫功能
let getDate = "2020-04-10T18:46:42+08:00"
let x = self.dateInRequiredFormat(stringDate: getDate, requiredFormat : "HH:mm")
print("date:- \(x)")
日期格式化功能
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
}