Kilian
Kilian

Reputation: 2282

Using DateFormatter to parse an esoteric date string

I would like to use Foundation's DateFormatter to parse a datestring of the rather weird format /Date(1488335133000+0100)/ (representing 2017-03-01 03:25:33). As far as I can tell this describes the date as milliseconds since 1970 with a timezone of GMT+1 specified as well.

I can't however find a way to specify a format string for milliseconds or seconds as a unix timestamp. Is this even possible?

In case that's not possible, what would be the best option for parsing this date correctly? I'm currently resorting to picking apart the string until I have the milliseconds and timezone, dividing the milliseconds by 1000 and creating a new date object via Date(timeIntervalSince1970: seconds). Not quite sure how the timezone is supposed to play into this though.

Upvotes: 0

Views: 94

Answers (1)

Code Different
Code Different

Reputation: 93151

DateFormatter can't handle this. Use NSRegularExpression to pick apart the components:

let str = "/Date(1488335133000+0100)/"

let regex = try! NSRegularExpression(pattern: "/Date\\((\\d+)(\\+|-)(\\d{2})(\\d{2})\\)/", options: [])
if let match = regex.firstMatch(in: str, options: [], range: NSMakeRange(0, str.characters.count)) {
    let nsstr = str as NSString
    let millisecond = Double(nsstr.substring(with: match.rangeAt(1)))!
    let sign        = nsstr.substring(with: match.rangeAt(2))
    let hour        = Double(nsstr.substring(with: match.rangeAt(3)))!
    let minute      = Double(nsstr.substring(with: match.rangeAt(4)))!

    let offset = (sign == "+" ? 1 : -1) * (hour * 3600.0 + minute * 60.0)
    let date   = Date(timeIntervalSince1970: millisecond / 1000 + offset)

    print(date)
}

Upvotes: 1

Related Questions