Convert String to NSDate in Swift

2019-02-16 00:45发布

问题:

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

回答1:

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



回答2:

You just use the wrong function at the last line of your above mentioned code

 var dateString = "01-02-2010"
 var dateFormatter = NSDateFormatter()
 dateFormatter.dateFormat = "yyyy-MM-dd"
 var dateFromString = dateFormatter.dateFromString(dateString)


回答3:

Based on Wolverine's code, I've written a function for Swift 3 and iOS10. Feel free to use:

func convertStringTimestampToStringDate(_ dateandTime: String) -> String {

let string : String = dateandTime
let timeinterval : TimeInterval = (string as NSString).doubleValue
let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)

let dateFormater : DateFormatter = DateFormatter()
dateFormater.dateFormat = "MMM dd, yyyy, HH:mm a"
dateFormater.amSymbol = "AM"
dateFormater.pmSymbol = "PM"

let backToString = dateFormater.string(from: dateFromServer as Date)
print(dateFormater.string(from: dateFromServer as Date))
return backToString }

This should bring a solution like e.g.: "Oct 20, 2016, 03:30 AM" from an timestamp as input.



回答4:

Convert Date format in Swift:

let myDate = "2016-09-19 01:25:17"
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd HH:mm:ss"

let date = dateFormat.dateFromString(myDate)
dateFormat.dateFormat =  "yyyy-MM-dd"
let  newDate =  dateFormat.stringFromDate(date!)

print(newDate)