0

I have been following the multiple examples to convert my iso date string to a local date String and have got the following working:

    func ISOStringToLocal(ISODateString: String) -> String {
        let dateFormatterGet = DateFormatter()
        dateFormatterGet.timeZone = NSTimeZone(name: "UTC")! as TimeZone
        dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" //Input Format with seconds
        // dateFormatter.dateFormat = " yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" //Input Format with milliseconds

        let dateFormatterPrint = DateFormatter()
        dateFormatterPrint.dateFormat = "dd-MMM-yyyy hh:mm:ss"

        if let date = dateFormatterGet.date(from: ISODateString) {
            return dateFormatterPrint.string(from: date)
        } else {
            return ""
        }
    }

How do I allow the the dateFormatterGet to accept another input format for milliseconds as well as seconds?

KvnH
  • 496
  • 1
  • 9
  • 30
  • Parse the date string for example with regex to detect the format or use one date format and instead of `return ""` try the other format – vadian Jul 24 '18 at 20:49

1 Answers1

1

You'll have to try both formats, one after the other:

func ISOStringToLocal(_ dateString: String) -> String {
    let dateFormatterGet = DateFormatter()
    dateFormatterGet.timeZone = TimeZone(identifier: "UTC")
    dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" // with seconds

    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "dd-MMM-yyyy hh:mm:ss"

    if let date = dateFormatterGet.date(from: dateString) {
        return dateFormatterPrint.string(from: date)
    } else {
        dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SSSZZZZZ" // with millis
        if let date = dateFormatterGet.date(from: dateString) {
            return dateFormatterPrint.string(from: date)
        }
        return ""
    }
}

print(ISOStringToLocal("2017-07-01T13:24:00+02:00"))
print(ISOStringToLocal("2017-07-01T13:24:00:123+02:00"))
Gereon
  • 17,258
  • 4
  • 42
  • 73
  • 4
    1. You do not need to set the timeZone of `dateFormatterGet`. The timezone is part of the string being parsed. 2. You need to set the locale of `dateFormatterGet` to `en_US_POSIX`. 3. The `hh` needs to be `HH`. 4. This is more of a choice by the OP but `dateFormatterPrint` should use date/time style, not a hardcoded format. – rmaddy Jul 24 '18 at 21:04