I want to convert a string with the format 2023-10-10 15:30:40.345T+5:30
to date, which is something like 10 Oct 2023
.
I tried with the following dateFormat
, it failed to parse and printed "failed to parse timestamp"
let timestampString = "2023-10-10 15:30:40.345T+5:30"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS'T'ZZZZZ"
if let timestamp = dateFormatter.date(from: timestampString) {
dateFormatter.dateFormat = "d MMM yyyy"
let formattedDate = dateFormatter.string(from: timestamp)
print(formattedDate)
} else {
print("failed to parse timestamp")
}
2
Answers
The Unicode standard specification for dates doesn’t support time zones with a single hour digit.
It must be
+05:30
A possible solution is to add – if necessary – the leading zero with Regular Expression
It seems there is a small issue with the timestamp string. The correct format for parsing the provided timestamp string is "yyyy-MM-dd HH:mm:ss.SSS’T’ZZZZZ" which means referring to the input timestamp string "2023-10-10 15:30:40.345T**+0**5:30",The zero was missing in the input string. Here’s the modified code:
This code should now correctly parse the provided timestamp string and print the formatted date. If you have any further questions or need additional modifications, feel free to ask!