aircraft
aircraft

Reputation: 26896

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?

Upvotes: 8

Views: 15036

Answers (2)

MhmdRizk
MhmdRizk

Reputation: 1721

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

Upvotes: 1

fzh
fzh

Reputation: 688

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)

Upvotes: 10

Related Questions