tags:

views:

570

answers:

1

I'm actually working with fbconnect and I'm trying to get a unix time that represents a month ago. I'm really confused about this since 1970 thing. Cause some body give me a point in the right direction?

+6  A: 

With the Unix epoch, time "0" is midnight on January 1st, 1970. Every second since, another second has been added; the time right now as I write this is:

>>> import time
>>> time.time()
1257023557.94208

Most systems communicate using the Unix epoch because it is easy, de-facto standard, and allows integer arithmetic. You can get an NSTimeInterval representing the duration since the epoch from an NSDate like this:

NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];

An NSTimeInterval is just a double. If you want an integer -- which I imagine fbconnect needs -- just convert it (untested):

NSString *strtimestamp = [NSString stringWithFormat:"%u", [timestamp unsignedIntegerValue]];

Remember, it's just a count. You can subtract an hour by subtracting 3600 (60 * 60), add a day by adding 86400 (24 * 60 * 60), and so forth; however, it's better in your case to start with an NSDate representing the specific time you want and allowing the library to do the arithmetic for you.

NSDate is probably just a wrapper around these timestamps.

Jed Smith
Note that daylight savings, leap seconds, etc. make simply adding and subtracting seconds problematic in those edge cases. If your app doesn't depend on them, great, but if it needs to handle them properly a library that deals with them is advisable.
ceejayoz
however, once you get beyond days when performing calendar arithmetic, things get much more complicated (different days per month, leap years, time zones, daylight savings). Use library routines to figure out when last month is.
Michael Burr
@ceejayoz: No, it doesn't. Unix timestamps have never accounted for them, so there are multiple times in "real time" which the same Unix timestamp represented (the last in 2006, IIRC?). Daylight savings also does not factor into Unix timestamps at all, as they are timezone agnostic (they are seconds since a time, nothing more). Therefore, the arithmetic I present works in every case for Unix timestamps.
Jed Smith
@Jed Smith: you are right that Unix time does not take into account leap seconds or time zone shifts, but that means that if the OP wants to take such things into account, then a library is a good idea. A month ago is usually pretty easy - as long as you can agree on what is a month ago from the 31st or 30th of March, or 29th March in a non-leap year. And as long as you don't need a time in the range 02:00-03:00 on a Sunday when the local time switched between winter and summer (standard and daylight saving) time. Etc.
Jonathan Leffler
@Jonathan: So he gets an `NSDate` for "a month ago" and calls `timeIntervalSince1970` on it...
Jed Smith