Objectmapper: ISO8601DateTransform does not handle the full range of ISO8601 Date Formats

Created on 7 Jul 2015  路  5Comments  路  Source: tristanhimmelman/ObjectMapper

The ISO8601DateTransform only handles one case of the ISO8601 (Wikipedia) standard.

Sample Format that it handles:

2015-07-07T13:07:42Z with this date format "yyyy-MM-dd'T'HH:mm:ssZZZZZ".

However, dates could be in several different formats and still comply with the ISO8601 standard.

For Example:

2015-07-07T13:07:42.05Z includes milliseconds
20150707T130742Z uses the non-extended format
2015-188T13:07:42Z specifies the day of the year instead of month and day of the month.

Most helpful comment

Try this:

ISO8601ExtendedDateTransform.swift

/// ISO 8601 extended date format transform which contains milliseconds.
class ISO8601ExtendedDateTransform: DateFormatterTransform {

    init() {
        let formatter = NSDateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        super.init(dateFormatter: formatter)
    }

}

All 5 comments

It would be great if you could create a Pull Request with a fix and a test.

Thanks!

Why was this closed ? I am still having issues with simple dates like 2015-10-24T06:30:00

For dates that don't conform to the following format yyyy-MM-dd'T'HH:mm:ssZZZZZ, you will need to create your own subclass of DateFormatterTransform

Try this:

ISO8601ExtendedDateTransform.swift

/// ISO 8601 extended date format transform which contains milliseconds.
class ISO8601ExtendedDateTransform: DateFormatterTransform {

    init() {
        let formatter = NSDateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        super.init(dateFormatter: formatter)
    }

}

For iOS 10

`

class NativeISO8601DateTransform: TransformType {

public typealias Object = Date
public typealias JSON = String

public let dateFormatter: ISO8601DateFormatter

public init() {
    self.dateFormatter = ISO8601DateFormatter()
}

public init(dateFormatter: ISO8601DateFormatter) {
    self.dateFormatter = dateFormatter
}

open func transformFromJSON(_ value: Any?) -> Date? {
    if let dateString = value as? String {
        //remove milliseconds
        let range = dateString.startIndex..<dateString.endIndex
        let trimmedString = dateString.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression, range: range)

        return dateFormatter.date(from: trimmedString)
    }

    return nil
}

open func transformToJSON(_ value: Date?) -> String? {
    if let date = value {
        return dateFormatter.string(from: date)
    }

    return nil
}

}

`

Was this page helpful?
0 / 5 - 0 ratings