Swift 无法从格式“创建日期”;yyyy-MM-dd';T';HH:mm:ss+;00:00“;
我想从字符串转换为日期。 我是否在这里使用了正确的格式和“yyyy-MM-dd'T'HH:MM:ss+00:00”Swift 无法从格式“创建日期”;yyyy-MM-dd';T';HH:mm:ss+;00:00“;,swift,dateformatter,Swift,Dateformatter,我想从字符串转换为日期。 我是否在这里使用了正确的格式和“yyyy-MM-dd'T'HH:MM:ss+00:00” 问题在于: dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+00:00" +00:00需要替换为xxxx,例如: dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxx" 您的代码将成为: func format(_ format:String) -> St
问题在于:
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+00:00"
+00:00
需要替换为xxxx
,例如:
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxx"
您的代码将成为:
func format(_ format:String) -> String {
var date: Date?
let dateFormatterGet = DateFormatter()
let dateFormatterOutput = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxx"
dateFormatterOutput.dateFormat = format
if let d = dateFormatterGet.date(from: self) {
date = d
}
return dateFormatterOutput.string(from: date!)
}
注意:这里我假设您使用的日期字符串将包含时区+xx:xx(例如+02:00),依此类推。但是,对于不同的格式,您需要使用不同数量的x
(如果时区不包含Z,则使用较小的x
):
x
->-08,+0330xx
->-0800xxx
->-800,-075254xxxx
->-8:00,-07:52:54如果时区包含
Z
,那么我们使用大写X
annnnddddd,您输入了什么?你的问题是什么?为什么在日期格式中使用+00:00?
func format(_ format:String) -> String {
var date: Date?
let dateFormatterGet = DateFormatter()
let dateFormatterOutput = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxx"
dateFormatterOutput.dateFormat = format
if let d = dateFormatterGet.date(from: self) {
date = d
}
return dateFormatterOutput.string(from: date!)
}