I am looking for a Swifty way to generate a timestamp.
My macOS app logs some data and stamps it with the time the data was created. The data will then be sent across the network (as Data
) to be reconstructed on an iPad.
Is there any Swift class that will work to generate the timestamp? NSDate? NSTimeIntervalSince1970? CFAbsoluteTimeGetCurrent()
The requirements are:
- Store the timestamp in as few bytes as possible (pref.
Int
) - Have some semblance to real Earth time (I'd rather not generate my own time format)
- Millisecond accuracy
- Fast to construct
- iOS 9+, macOS 10.10+
You can send your
Date
converting it toData
(8-bytes floating point) and back toDate
as follow:Playground Testing
Use
TimeIntervalSince1970
type:Original answer was very inefficient.
Here is how I used Leo Dabus's answer.