skip to Main Content

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


  1. 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

    let timestampString = "2023-10-10 15:30:40.345T+5:30"
    let consolidatedTimestampString = timestampString.replacing(/([+-])(d:)/) {
        return $0.output.1 + "0" + $0.output.2
    }
    let dateFormatter = DateFormatter()
    
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS'T'xxx"
    if let timestamp = dateFormatter.date(from: consolidatedTimestampString) {
        dateFormatter.dateFormat = "d MMM yyyy"
        let formattedDate = dateFormatter.string(from: timestamp)
        print(formattedDate)
    } else {
        print("failed to parse timestamp")
    }
    
    Login or Signup to reply.
  2. 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:

    let timestampString = "2023-10-10 15:30:40.345T+05: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")
    }
    

    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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search