iPhone Guy iPhone Guy - 2 months ago 6
Swift Question

Convert String to NSDate in Swift

How to convert this date to

NSDate


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


Expected Output:

12/01/2014


I tried this. But I got nil.

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

Answer

"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.

Comments