views:

1692

answers:

3

I'm seeing an odd behavior with trying to get seconds since epoch in objective C. This:

NSString *nowTimestamp = [NSString stringWithFormat:@"%d", 
                             [[NSDate date] timeIntervalSince1970]];

Outputs 15907296, when the current timestamp should be 1243555623 (05/28/2009 @ 7:08pm EST). The system time on the iPhone is correct. I can't figure out for the life of me what I'm doing wrong. Any recommendations?

+1  A: 

Are you sure that the result from NSDate is a decimal int? The docs say it is a double. You could try casting.

Also, sometimes you will get a pointer value back instead of the actual value, if something is a NSNumber under the covers, you may need to use intValue, or doubleValue to get the actual content of what is at the address.

Heat Miser
Yes, you'll need %f
Heat Miser
+8  A: 

timeIntervalSince1970 returns an NSTimeInterval, which is a typedef for double; %d is not the right formatter to print a double (you want %f).

smorgan
Ha, thanks, I knew I was doing something stupid.
Parrots
+2  A: 

As the return from [[NSDate date] timeIntervalSince1970]; is a double, you could try this:

NSString *nowTimestamp = [NSString stringWithFormat:@"%f", 
                         [[NSDate date] timeIntervalSince1970]];
Abizern