Get current NSDate in timestamp format
Here's what I use:
NSString * timestamp = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
(times 1000 for milliseconds, otherwise, take that out)
If You're using it all the time, it might be nice to declare a macro
#define TimeStamp [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000]
Then Call it like this:
NSString * timestamp = TimeStamp;
Or as a method:
- (NSString *) timeStamp {
return [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
}
As TimeInterval
- (NSTimeInterval) timeStamp {
return [[NSDate date] timeIntervalSince1970] * 1000;
}
NOTE:
The 1000 is to convert the timestamp to milliseconds. You can remove this if you prefer your timeInterval in seconds.
Swift
If you'd like a global variable in Swift, you could use this:
var Timestamp: String {
return "\(NSDate().timeIntervalSince1970 * 1000)"
}
Then, you can call it
println("Timestamp: \(Timestamp)")
Again, the *1000
is for miliseconds, if you'd prefer, you can remove that. If you want to keep it as an NSTimeInterval
var Timestamp: NSTimeInterval {
return NSDate().timeIntervalSince1970 * 1000
}
Declare these outside of the context of any class and they'll be accessible anywhere.
use [[NSDate date] timeIntervalSince1970]