3

I have a String in following format

"/Date(573465600000-0800)/"

How do I convert this to regular NSDate object?

jscs
  • 63,694
  • 13
  • 151
  • 195
Sam Shaikh
  • 1,596
  • 6
  • 29
  • 53
  • Similar question (with answer) here: http://stackoverflow.com/questions/27908219/parsing-json-date-to-swift, only without the timezone part. – Martin R Mar 04 '15 at 12:10
  • @Duaan: I does not give any error for me (and the result is "1988-03-04 08:00:00 +0000"). But, as I said, that code does not honour the time zone part "-0800", so you would have to add that. – Martin R Mar 04 '15 at 12:21
  • error is not in -800 part, it is in jsonData line, means inside IF. it is not identifying that part. I think I am putting Extension at wrong place, I do try , – Sam Shaikh Mar 04 '15 at 12:26

4 Answers4

8

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

Update for Swift 3 (Xcode 8):

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

        // Check prefix:
        guard scanner.scanString(prefix, into: nil)  else { return nil }

        // Read milliseconds part:
        var milliseconds : Int64 = 0
        guard scanner.scanInt64(&milliseconds) else { return nil }
        // Milliseconds to seconds:
        var timeStamp = TimeInterval(milliseconds)/1000.0

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

        // Check suffix:
        guard scanner.scanString(suffix, into: nil) else { return nil }

        // Success! Create NSDate and return.
        self.init(timeIntervalSince1970: timeStamp)
    }
}

Example:

if let theDate = Date(jsonDate: "/Date(573465600000-0800)/") {
    print(theDate)
} else {
    print("wrong format")
}
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks alot, I earlier saw your answer, but mistake was that I was not placing Extension at right place ;) Issue is solved. – Sam Shaikh Mar 04 '15 at 12:56
  • let timeStampToDate = (String(describing: obj?["departTimestamp"] as! NSNumber)) as String var time = Date(jsonDate:"/Date\(timeStampToDate)/") Here my time is coming nil – Rahul Gupta Feb 17 '17 at 04:29
  • @RahulGupta: That is because the string `timeStampToDate` contains the word "Optional". You should avoid `String(describing:...)` and properly unwrap the optionals instead. – Martin R Feb 17 '17 at 05:54
  • @MartinR thnx dear but I change the format and it works let timeSt = Date(jsonDate:"/Date(\(timeStampToDate))/") – Rahul Gupta Feb 17 '17 at 07:24
4
var date:NSDate = NSDate(timeIntervalSince1970: timeInterval)
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
Javier Flores Font
  • 2,075
  • 15
  • 13
3

let myTimeStamp = "1463689800000.0"

    let dateTimeStamp = NSDate(timeIntervalSince1970:Double(myTimeStamp)!/1000)  //UTC time

    let dateFormatter = NSDateFormatter()
    dateFormatter.timeZone = NSTimeZone.localTimeZone() //Edit
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle


    let strDateSelect = dateFormatter.stringFromDate(dateTimeStamp)
    print(strDateSelect) //Local time
    let dateFormatter2 = NSDateFormatter()
    dateFormatter2.timeZone = NSTimeZone.localTimeZone()
    dateFormatter2.dateFormat = "yyyy-MM-dd"

    let date3 = dateFormatter.dateFromString(strDateSelect)

    datepicker.date = date3!
Paresh Hirpara
  • 487
  • 3
  • 10
2

Swift 4

let date = Date(timeIntervalSince1970: TimeInterval(1463689800000.0))
Ahmadreza
  • 6,950
  • 5
  • 50
  • 69