如何从 swift 3 中的字符串中获取日期?
How to get Date from String in swift 3?
我已将时间戳保存在数据库中,例如:
"NSDate()" // which save Date like this: 2017-03-10 22:53:30 +0000
现在我需要从这个字符串中获取日期,我已经尝试了所有格式,但它一直返回 nil。
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss ZZZ"
dateFormatter.locale = Locale(identifier: "en_US")
print(dateFormatter.date(from: "2017-03-10 22:53:30 +0000") ?? "No Value") // always return No Value
在这里我尝试了很多格式,例如:
yyyy-MM-dd hh:mm:ss +zzzz
yyyy-MM-dd hh:mm:ss xx
看过很多答案,但没有答案适用于这种格式的日期“2017-03-10 22:53:30 +0000”
军事时间(24 值小时)使用首都'H'。为您的格式字符串试试这个:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
hh
是一个12小时的小时数。如果您有 24 小时的小时填充,则需要 HH
。查看 http://nsdateformatter.com 了解有关 NSDateFormatter 格式的更多详细信息。
我在将 String
转换为 Date
时使用此代码。
(Swift 3)
extension String
{
func toDate( dateFormat format : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
if let date = dateFormatter.date(from: self)
{
return date
}
print("Invalid arguments ! Returning Current Date . ")
return Date()
}
}
然后像 一样打电话。 .
print ( "2016-06-20T13:01:46.457+02:00".toDate(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") )
//Capital HH for 24-Hour Time
我已将时间戳保存在数据库中,例如:
"NSDate()" // which save Date like this: 2017-03-10 22:53:30 +0000
现在我需要从这个字符串中获取日期,我已经尝试了所有格式,但它一直返回 nil。
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss ZZZ"
dateFormatter.locale = Locale(identifier: "en_US")
print(dateFormatter.date(from: "2017-03-10 22:53:30 +0000") ?? "No Value") // always return No Value
在这里我尝试了很多格式,例如: yyyy-MM-dd hh:mm:ss +zzzz yyyy-MM-dd hh:mm:ss xx
看过很多答案,但没有答案适用于这种格式的日期“2017-03-10 22:53:30 +0000”
军事时间(24 值小时)使用首都'H'。为您的格式字符串试试这个:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
hh
是一个12小时的小时数。如果您有 24 小时的小时填充,则需要 HH
。查看 http://nsdateformatter.com 了解有关 NSDateFormatter 格式的更多详细信息。
我在将 String
转换为 Date
时使用此代码。
(Swift 3)
extension String
{
func toDate( dateFormat format : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
if let date = dateFormatter.date(from: self)
{
return date
}
print("Invalid arguments ! Returning Current Date . ")
return Date()
}
}
然后像 一样打电话。 .
print ( "2016-06-20T13:01:46.457+02:00".toDate(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") )
//Capital HH for 24-Hour Time