如何将 Swift 中的“2020-04-10T18:46:42+08:00”转换为“18:46”?
How can I convert "2020-04-10T18:46:42+08:00" to "18:46" in Swift?
如何将 Swift 中的“2020-04-10T18:46:42+08:00”转换为“18:46”?
我尝试格式化它,但找不到更好的解决方案。
您可以使用Calendar
class component(_:from:)
方法获取小时和分钟。
let calendar = Calendar.current
calendar.component(.hour, from: date) // hour
calendar.component(.minute, from: date) // minute
调用函数
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
}
如何将 Swift 中的“2020-04-10T18:46:42+08:00”转换为“18:46”?
我尝试格式化它,但找不到更好的解决方案。
您可以使用Calendar
class component(_:from:)
方法获取小时和分钟。
let calendar = Calendar.current
calendar.component(.hour, from: date) // hour
calendar.component(.minute, from: date) // minute
调用函数
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
}