I have a string like 20230914T07:37:43.000Z. I want to append single quotes and hyphens, and my result should be like this: 2023-09-14'T'07:37:43.000Z.
I have tried the code below, but a backslash is automatically added to my string, resulting in 2023-09-14'T'07:37:43.000Z.
Code:
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'
I have tried both options, but I still get a backslash automatically added to my string.
Question: How to append single quotes and hyphens without black slash?
Can someone please explain to me how to do this, I've tried with the above code but have no results yet. Please Correct me if I'm doing wrong.
Any help would be greatly appreciated
There's no reason to add apostrophes to the
welcomestring. The apostrophes are only needed around theTin thedateFormatof the date formatter to indicate that theTis to be treated literally and not as a format specifier.You should also avoid adding the hyphens to the
welcomestring and simply remove the hyphens from thedateFormat. The whole idea of adateFormatis to choose a date format that matches the strings you will be parsing.With all of that in mind, your code simply becomes:
Or you may wish to use
ISO8601DateFormatterto work with strings in one of the supported ISO8601 formats.