Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 208
aircraft Avatar asked Dec 05 '16 03:12

aircraft


People also ask

How do I convert a string to a date in Swift?

dateFormat = "yyyy-MM-dd'T'HH:mm:ss" dateFormatter. timeZone = NSTimeZone(name: "UTC") let date = dateFormatter. dateFromString("2015-04-01T11:42:00") // change to a readable time format and change to local time zone dateFormatter. dateFormat = "EEE, MMM d, yyyy - h:mm a" dateFormatter.

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

What is timestamp in Swift?

Save. What is timestamp? A timestamp is that which contain some characters that are in an encoded form which will contain any event, date or time etc. For more information, you can also go through from here.


1 Answers

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)
like image 146
fzh Avatar answered Sep 28 '22 14:09

fzh