iPhone Guy iPhone Guy - 7 months ago 35
Swift Question

Convert String to NSDate in Swift

How to convert this date to


datestring = /Date(147410000000)/ //String from server response

Expected Output:


I tried this. But I got nil.

let dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let date = dateFormatter.dateFromString(datestring)
return date


"147410000000", i think this the time-interval which you are getting from server.

In your case,you need to trim the string and convert it From /Date(147410000000)/ to 147410000000

    var string : String = "1408709486" // (Put your string here)

    var timeinterval : NSTimeInterval = (string as NSString).doubleValue // convert it in to NSTimeInteral

    var dateFromServer = NSDate(timeIntervalSince1970:timeinterval) // you can the Date object from here

    println(dateFromServer) // for My Example it will print : 2014-08-22 12:11:26 +0000

    // Here i create a simple date formatter and print the string from DATE object. you can do it vise-versa. 

    var dateFormater : NSDateFormatter = NSDateFormatter()
    dateFormater.dateFormat = "yyyy-MM-dd"
    println(dateFormater.stringFromDate(dateFromServer)) // And then i can get the string like this : 2014-08-22

Check the comment section. Martin's comment will also help you to resolve your problem.