Ali*_*RAL 5 nsdate nsdateformatter ios swift
我知道将Date转换为String // String to Date
同
let formatter = DateFormatter()
formatter.dateFormat = "yyyy MM dd"
let date = formatter.date ( from: String )
Run Code Online (Sandbox Code Playgroud)
要么
let string = formatter.string ( from: Date )
Run Code Online (Sandbox Code Playgroud)
但是我希望将日期格式转换为日期,格式为 "yyyy-MM-dd'T'HH:mm:ssZ"到日期格式的"yyyy-MM-dd".
无论如何用一条线做到这一点?
回答您的问题:否。
您可以创建一个日期/字符串扩展名,它可以在一行中解决您的问题。请注意,Dateobject 是一个日期对象。它没有任何格式(如字符串)。
可以帮助你:
extension String {
func convertDateString() -> String? {
return convert(dateString: self, fromDateFormat: "yyyy-MM-dd'T'HH:mm:ssZ", toDateFormat: "yyyy-MM-dd")
}
func convert(dateString: String, fromDateFormat: String, toDateFormat: String) -> String? {
let fromDateFormatter = DateFormatter()
fromDateFormatter.dateFormat = fromDateFormat
if let fromDateObject = fromDateFormatter.date(from: dateString) {
let toDateFormatter = DateFormatter()
toDateFormatter.dateFormat = toDateFormat
let newDateString = toDateFormatter.string(from: fromDateObject)
return newDateString
}
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
使用一行代码:
let newDateString = "my date string".convertDateString()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1362 次 |
| 最近记录: |