Get current NSDate in timestamp format

Supertecnoboff picture Supertecnoboff · Mar 12, 2014 · Viewed 153.5k times · Source

I have a basic method which gets the current time and sets it in a string. However, how can I get it to format the current date & time in a UNIX since-1970 timestamp format?

Here is my code:

NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh-mm"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];

Is it possible to use NSDateFormatter to change the 'resultString' into a timestamp?

Answer

Logan picture Logan · Mar 12, 2014

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.