Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Objective-c equivalent to java timestamp?

I've not found a answer to this question anywhere, but this seems like a typical problem: I have in Objective-C a "NSDate timestamp" that looks like "2010-07-14 16:30:41 +0200". The java timestamp is just a long integer (for example:"976712400000").

So, my question is: What is a Objective-c equivalent to java timestamp?

Thanks in advance for helping.

like image 286
jcdmb Avatar asked Nov 29 '22 18:11

jcdmb


2 Answers

Although @lordsandwich's answer is correct, you can also directly use the NSDate timeIntervalSince1970 method, instead of 'making' the 1970 NSDate yourself.

That would work like this:

NSDate *past = [NSDate date];
NSTimeInterval oldTime = [past timeIntervalSince1970];
NSString *unixTime = [[NSString alloc] initWithFormat:@"%0.0f", oldTime];

As when you use this you don't unnecessarily add a new object to the autorelease pool, I think it's actually better to use this method.

like image 173
Douwe Maan Avatar answered Dec 10 '22 02:12

Douwe Maan


You can convert the format that NSDAte gives you to unix time by substracting the starting date of unix time which is the 1st of January 1970. NSTimeInterval is simply the difference between two dates and you can get that in number of seconds:

NSDate * past = [NSDate date];
NSTimeInterval oldTime = [past timeIntervalSinceDate:[NSDate dateWithNaturalLanguageString:@"01/01/1970"]];
NSString * unixTime = [[NSString alloc] initWithFormat:@"%0.0f", oldTime];
like image 41
theprole Avatar answered Dec 10 '22 03:12

theprole