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 welcome
string. The apostrophes are only needed around the T
in the dateFormat
of the date formatter to indicate that the T
is to be treated literally and not as a format specifier.
You should also avoid adding the hyphens to the welcome
string and simply remove the hyphens from the dateFormat
. The whole idea of a dateFormat
is to choose a date format that matches the strings you will be parsing.
With all of that in mind, your code simply becomes:
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
}
Or you may wish to use ISO8601DateFormatter
to work with strings in one of the supported ISO8601 formats.