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.
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.
Hi Neha,
I believe this is the NSDate's selector you're looking for:
- (NSTimeInterval)timeIntervalSince1970
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];