views:

1094

answers:

2

Hi all,

How to convert an NSDate into Unix timestamp? I've read many posts which do the reverse. But I'm not finding anything related to my question.

Thanx in advance.

+5  A: 

Hi Neha,

I believe this is the NSDate's selector you're looking for:

- (NSTimeInterval)timeIntervalSince1970
Vnuce
Does this return a unix timestamp if provided with an nsdate?
neha
Yes, this is exactly what you're looking for. UNIX measures time in seconds since jan 1st 1970, and this method returns the interval between the receiver (the NSDate you provide) and the first instant of 1 January 1970, GMT. NSTimeInterval is actually a typedef of double.
Vnuce
+2  A: 

A Unix timestamp is the number of seconds since 00:00:00 UTC January 1, 1970. It's represented by the type time_t, which is usually a signed 32-bit integer type (long or int).

iOS provides -(NSTimeInterval)timeIntervalSince1970 for NSDate objects which returns the number of seconds since 00:00:00 GMT January 1, 1970. NSTimeInterval is a double floating point type so you get the seconds and fractions of a second.

Since they both have the same reference (midnight 1Jan1970 UTC) and are both in seconds the conversion is easy, convert the NSTimeInterval to a time_t, rounding or truncating depending on your needs:

time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];
progrmr
This function shows me correct date but time is wrong. It doesn't match the system time.
neha
Unix time is UTC (GMT), India is UTC+5.5. Is it off by 5.5 hours?
progrmr
Yes, almost.. What should be done to correct this?
neha
Your system time is showing time in your local time zone, which is fine. Unix timestamp is not local time, it is always UTC time, it differs by +5:30 in India, -7:00 from here. That's correct.
progrmr
Thanx progrmr, it really helped..
neha