How to convert NSDate into unix timestamp iphone sdk?

145,059

Solution 1

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

- (NSTimeInterval)timeIntervalSince1970

Solution 2

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];

Solution 3

You can create a unix timestamp date from a date this way:

NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];

Solution 4

- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strTime = [objDateformat stringFromDate:[NSDate date]];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);

        NSString *strTimeStamp = [Nsstring stringwithformat:@"%lld",milliseconds];
        NSLog(@"The Timestamp is = %@",strTimestamp);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.

Solution 5

Swift

Updated for Swift 3

// current date and time
let someDate = Date()

// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970

Notes

  • timeIntervalSince1970 returns TimeInterval, which is a typealias for Double.

  • If you wanted to go the other way you could do the following:

      let myDate = Date(timeIntervalSince1970: myTimeStamp)
    
Share:
145,059

Related videos on Youtube

neha
Author by

neha

Updated on March 01, 2020

Comments

  • neha
    neha about 4 years

    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.

  • neha
    neha almost 14 years
    Does this return a unix timestamp if provided with an nsdate?
  • BAndonovski
    BAndonovski almost 14 years
    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.
  • neha
    neha almost 14 years
    This function shows me correct date but time is wrong. It doesn't match the system time.
  • progrmr
    progrmr almost 14 years
    Unix time is UTC (GMT), India is UTC+5.5. Is it off by 5.5 hours?
  • progrmr
    progrmr almost 14 years
    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.
  • JeroenEijkhof
    JeroenEijkhof almost 13 years
    But then how do use it? Can I use it in my calculations later? I have one UNIX timestamp from a PHP database online and then this one. I want to compare the two in order to make a decision to download the latest data about an object.
  • JeroenEijkhof
    JeroenEijkhof almost 13 years
    I'm just doing this now: int unixTime = floor([piece.piece_last_view timeIntervalSince1970]) where piece.piece.last_view is an NSDate
  • ıɾuǝʞ
    ıɾuǝʞ over 12 years
    To get a string (28/11/2011 14:14:13 <-> 1322486053) : [NSString stringWithFormat:@"%.0f", [aDate timeIntervalSince1970]];
  • aroth
    aroth about 11 years
    Is it just me or is this method frustrated by Daylight Saving Time? I had an app that was working fine, and then suddenly all of the timestamps that it generated were off by exactly 1 hour (as compared to timestamps generated here).
  • Esko918
    Esko918 over 10 years
    The method is changed by the time set on the device in general. I did a test where i got the timestamp at 12pm then changed around the time on the iPad to about 8pm and the difference in the two numbers were extremely high. If the timestamp was no device time dependent the numbers should have been off by mere seconds, but in this case I had to conclude that the time on the iPad does affect the unixTimeStamp
  • Matt Wolfe
    Matt Wolfe over 10 years
    This is wrong, timeIntervalSince1970 returns a TimeInterval which is actually a double.
  • k3a
    k3a almost 10 years
    I am correcting my answer - it really seems to be equal. Although time(NULL) may be a tiny bit faster as it's not calling obj-c runtime. :P Test code NSLog(@"time(NULL) = %d ; timeIntervalSince1970 = %d", (int)time(NULL), (int)[[NSDate date] timeIntervalSince1970]);
  • Tapan Thaker
    Tapan Thaker almost 10 years
    I have faced problems with [[NSDate date]timeIntervalSince1970]. They seem to consider the region you are in as well.
  • k3a
    k3a almost 10 years
    Yes, this is what I think I experienced that day but on iOS7 Simulator and iOS6 device with GMT+2 timezone they now seem equal... Anyway, time(NULL) works always :)
  • Hemang
    Hemang almost 9 years
    Why you're setting hour and minute to 0 in components? Also, how it'll give you exact UTC based on this : [[NSTimeZone systemTimeZone] secondsFromGMT]] ? Please explain little.
  • marsbear
    marsbear over 7 years
    @Esko918 Well of course. The Unix time describes the number of seconds from 1970 till the point in time you want to specify ("now" in this case). If you change the time on your iPad, you effectively change "now" to some other time and hence the difference in the time stamps.
  • marsbear
    marsbear over 7 years
    @Esko918 The question is still relevant, and such are the answers and the details in the comments.
  • Rahul K Rajan
    Rahul K Rajan over 7 years
    Hi friend it helped me