Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 18-digit current timestamp in Swift?

Tags:

I want to get current timestamp like this:

636110767775716756​ 

However, when I do :

NSDate().timeIntervalSince1970 

It returns a value like this:

1475491615.71278 

How do I access current time stamp ticks in the format I want? I check the dates from here:

like image 328
The Cook Avatar asked Oct 03 '16 10:10

The Cook


People also ask

How do you subtract two dates in Swift?

let calendar = NSCalendar. current as NSCalendar // Replace the hour (time) of both dates with 00:00 let date1 = calendar. startOfDay(for: startDateTime) let date2 = calendar. startOfDay(for: endDateTime) let flags = NSCalendar.


2 Answers

You seem be looking for what DateTime.Ticks is in C#, i.e. the time since 0001-01-01 measured in 100-nanosecond intervals.

The code from your provided link Swift: convert NSDate to c# ticks can be translated to Swift easily:

// Swift 2: extension NSDate {     var ticks: UInt64 {         return UInt64((self.timeIntervalSince1970 + 62_135_596_800) * 10_000_000)     } }  // Swift 3: extension Date {     var ticks: UInt64 {         return UInt64((self.timeIntervalSince1970 + 62_135_596_800) * 10_000_000)     } } 

Example (Swift 3):

let ticks = Date().ticks print(ticks) // 636110903202288256 

or as a string:

let sticks = String(Date().ticks) print(sticks) 

And while are are at it, the reverse conversion from ticks to Date would be

// Swift 2: extension NSDate {     convenience init(ticks: UInt64) {         self.init(timeIntervalSince1970: Double(ticks)/10_000_000 - 62_135_596_800)     } }  // Swift 3: extension Date {     init(ticks: UInt64) {         self.init(timeIntervalSince1970: Double(ticks)/10_000_000 - 62_135_596_800)     } } 

Example (Swift 3):

let date = Date(ticks: 636110903202288256) 
like image 136
Martin R Avatar answered Sep 22 '22 10:09

Martin R


Here is a solution that I find very elegant. I extended NSDate (although it's just Date now in Swift 3) to include a toMillis() func which will give you the Int64 value of the date object that you're working with.

extension Date {     func toMillis() -> Int64! {         return Int64(self.timeIntervalSince1970 * 1000)     } } 

Usage:

let currentTimeStamp = Date().toMillis() 

Cheers

like image 33
Hermann Kuschke Avatar answered Sep 25 '22 10:09

Hermann Kuschke