如何在Swift中添加单引号?

ktca8awb  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(119)

我有一个字符串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'

我已经尝试了这两个选项,但我仍然得到一个反斜杠自动添加到我的字符串。
问:如何在没有黑色斜杠的情况下追加单引号和连字符?
有人可以请向我解释如何做到这一点,我已经尝试了上述代码,但还没有结果。如果我做错了请纠正我。
任何帮助将不胜感激

nzk0hqpo

nzk0hqpo1#

没有理由在welcome字符串中添加撇号。在日期格式化程序的dateFormat中,仅在T周围需要撇号,以表明T将按字面意思处理,而不是作为格式说明符。
您还应该避免将连字符添加到welcome字符串中,而只需从dateFormat中删除连字符。dateFormat的整个思想是选择一个与您将要解析的字符串相匹配的日期格式。
考虑到所有这些,你的代码就变成了:

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyyMMdd'T'HH:mm:ss.SSSZ"

var welcome = "20230914T07:37:43.000Z"

if let date = dateFormatterGet.date(from: welcome) {
    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = formatter

    return dateFormatterPrint.string(from: date)
} else {
    // return some indicator of failure
}

或者您可能希望使用ISO8601DateFormatter来处理受支持的ISO8601格式之一的字符串。

相关问题