Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting UIDatePicker result to unix timestamp

Tags:

ios

swift

swift3

My issue is trying to convert a Date Picker result into a unix timestamp. My client is adamant that it'd be saved as a unix timestamp into Firebase database. Im also quite new to the swift so...

let myTimeStamp = NSDate(timeIntervalSince1970: self.datePicker?.date)

this is the result of datePicker: 2016-12-03 00:56:00 +0000 This is the error: Cannot convert value of type 'Date?' to expected argument type 'TimeInterval' (aka 'Double')

Please help sirs & ma'ams!

like image 523
CRey Avatar asked Dec 24 '22 23:12

CRey


2 Answers

You already have the Date. Since you want the timestamp, call:

let myTimeStamp = self.datePicker?.date.timeIntervalSince1970

myTimeStamp will be an NSTimeInterval with a value in Unix time.

like image 89
rmaddy Avatar answered Jan 05 '23 01:01

rmaddy


Including swift 5+ **Pass date like yourDatePicker.date **

 func getTimeStampFromDate(date: Date) -> String {
    return String(format: "%.0f", (date.timeIntervalSince1970 * 1000))
}
like image 38
thevikasnayak Avatar answered Jan 05 '23 01:01

thevikasnayak