Sam Shaikh Sam Shaikh - 6 months ago 166
Swift Question

Convert timestamp into NSDate swift?

There are many posts regarding this question in Objective-C, yet I can't find any solid answer in Swift Programming language.

I have a String in following format

"/Date(573465600000-0800)/"


How do I convert this to regular NSDate object?

Answer

The first part "573465600000" is the time since the Unix epoch in milliseconds, and the second part "-0800" is a time zone specification.

Here is a slight modification of Parsing JSON (date) to Swift which also covers the time zone part:

extension NSDate {
    convenience init?(jsonDate: String) {
        let prefix = "/Date("
        let suffix = ")/"
        let scanner = NSScanner(string: jsonDate)

        // Check prefix:
        if scanner.scanString(prefix, intoString: nil) {

            // Read milliseconds part:
            var milliseconds : Int64 = 0
            if scanner.scanLongLong(&milliseconds) {
                // Milliseconds to seconds:
                var timeStamp = NSTimeInterval(milliseconds)/1000.0

                // Read optional timezone part:
                var timeZoneOffset : Int = 0
                if scanner.scanInteger(&timeZoneOffset) {
                    let hours = timeZoneOffset / 100
                    let minutes = timeZoneOffset % 100
                    // Adjust timestamp according to timezone:
                    timeStamp += NSTimeInterval(3600 * hours + 60 * minutes)
                }

                // Check suffix:
                if scanner.scanString(suffix, intoString: nil) {
                    // Success! Create NSDate and return.
                    self.init(timeIntervalSince1970: timeStamp)
                    return
                }
            }
        }

        // Wrong format, return nil. (The compiler requires us to
        // do an initialization first.)
        self.init(timeIntervalSince1970: 0)
        return nil
    }
}

Example:

if let theDate = NSDate(jsonDate: "/Date(573465600000-0800)/") {
    println(theDate)
} else {
    println("wrong format")
}

Output:

1988-03-04 00:00:00 +0000