Get current date in milliseconds
Solution 1:
There are several ways of doing this, although my personal favorite is:
CFAbsoluteTime timeInSeconds = CFAbsoluteTimeGetCurrent();
You can read more about this method here. You can also create a NSDate object and get time by calling timeIntervalSince1970 which returns the seconds since 1/1/1970:
NSTimeInterval timeInSeconds = [[NSDate date] timeIntervalSince1970];
And in Swift:
let timeInSeconds: TimeInterval = Date().timeIntervalSince1970
Solution 2:
Casting the NSTimeInterval directly to a long overflowed for me, so instead I had to cast to a long long.
long long milliseconds = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
The result is a 13 digit timestamp as in Unix.
Solution 3:
NSTimeInterval milisecondedDate = ([[NSDate date] timeIntervalSince1970] * 1000);
Solution 4:
You can just do this:
long currentTime = (long)(NSTimeInterval)([[NSDate date] timeIntervalSince1970]);
this will return a value en milliseconds, so if you multiply the resulting value by 1000 (as suggested my Eimantas) you'll overflow the long type and it'll result in a negative value.
For example, if I run that code right now, it'll result in
currentTime = 1357234941
and
currentTime /seconds / minutes / hours / days = years
1357234941 / 60 / 60 / 24 / 365 = 43.037637652207
Solution 5:
extension NSDate {
func toMillis() -> NSNumber {
return NSNumber(longLong:Int64(timeIntervalSince1970 * 1000))
}
static func fromMillis(millis: NSNumber?) -> NSDate? {
return millis.map() { number in NSDate(timeIntervalSince1970: Double(number) / 1000)}
}
static func currentTimeInMillis() -> NSNumber {
return NSDate().toMillis()
}
}