我有一个字符串20230914T07:37:43.000Z
。我想附加单引号和连字符,我的结果应该是这样的:2023-09-14'T'07:37:43.000Z
。
我已经尝试了下面的代码,但是一个反斜杠被自动添加到我的字符串中,结果是2023-09-14'T'07:37:43.000Z
。
代码:
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = formatter
var welcome = "20230914T07:37:43.000Z"
welcome.insert("-", at: welcome.index(welcome.startIndex, offsetBy: 4))
welcome.insert("-", at: welcome.index(welcome.startIndex, offsetBy: 7))
print(2023-09-14T07:37:43.000Z)
// Option 1
welcome.insert(#"'"#, at: welcome.index(welcome.startIndex, offsetBy: 10))
welcome.insert(#"'"#, at: welcome.index(welcome.startIndex, offsetBy: 12))
// Option 2
welcome.insert("'", at: welcome.index(welcome.startIndex, offsetBy: 10))
welcome.insert("'", at: welcome.index(welcome.startIndex, offsetBy: 12))
dateString = welcome
let date: Date? = dateFormatterGet.date(from: dateString)
print(date) // -> nil
return dateFormatterPrint.string(from: date!); ////Crash
// Output: '2023-09-14'T'07:37:43.000Z'
我已经尝试了这两个选项,但我仍然得到一个反斜杠自动添加到我的字符串。
问:如何在没有黑色斜杠的情况下追加单引号和连字符?
有人可以请向我解释如何做到这一点,我已经尝试了上述代码,但还没有结果。如果我做错了请纠正我。
任何帮助将不胜感激
1条答案
按热度按时间nzk0hqpo1#
没有理由在
welcome
字符串中添加撇号。在日期格式化程序的dateFormat
中,仅在T
周围需要撇号,以表明T
将按字面意思处理,而不是作为格式说明符。您还应该避免将连字符添加到
welcome
字符串中,而只需从dateFormat
中删除连字符。dateFormat
的整个思想是选择一个与您将要解析的字符串相匹配的日期格式。考虑到所有这些,你的代码就变成了:
或者您可能希望使用
ISO8601DateFormatter
来处理受支持的ISO8601格式之一的字符串。