简体   繁体   中英

Convert a format string to timestamp in Swift

Before asking this question I have searched stack overflow but found some other language's answer. I did not find a post with Swift.

I have the string 2016-12 ,the time is 2016-12-01 00:00:00 . I want to convert to a timestamp , since 1970 using Greenwich Mean Time .

2016-12 → 1480521600.

2016-12 is a string formatted as year-month. I want to convert it to a timestamp

How can I convert it in Swift?

you can try this code:

var dfmatter = DateFormatter()
dfmatter.dateFormat="yyyy-MM-dd"
var date = dfmatter.date(from: "2016-12-1")
var dateStamp:TimeInterval = date!.timeIntervalSince1970
var dateSt:Int = Int(dateStamp)

Just to make it more clear: (SWIFT 3.0 -> 4.1)

 let yourDate = "2016-12-01"

 //initialize the Date Formatter
 let dateFormatter = DateFormatter()

 //specify the date Format  
 dateFormatter.dateFormat="yyyy-MM-dd"

 //get date from string 
 let dateString = dateFormatter.date(from: yourDate)

 //get timestamp from Date
 let dateTimeStamp  = dateString!.timeIntervalSince1970

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM