[ios] How to convert NSDate into unix timestamp iphone sdk?

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.

This question is related to ios iphone nsdate unix-timestamp

The answer is


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

 [NSString stringWithFormat: @"first unixtime is %ld",message,(long)[[NSDate date] timeIntervalSince1970]];

 [NSString stringWithFormat: @"second unixtime is %ld",message,[[NSDate date] timeIntervalSince1970]];

 [NSString stringWithFormat: @"third unixtime is %.0f",message,[[NSDate date] timeIntervalSince1970]]; 

first unixtime 1532278070

second unixtime 1532278070.461380

third unixtime 1532278070


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)
    

My preferred way is simply:

NSDate.date.timeIntervalSince1970;

As per @kexik's suggestion using the UNIX time function as below :

  time_t result = time(NULL);
  NSLog([NSString stringWithFormat:@"The current Unix epoch time is %d",(int)result]);

.As per my experience - don't use timeIntervalSince1970 , it gives epoch timestamp - number of seconds you are behind GMT.

There used to be a bug with [[NSDate date]timeIntervalSince1970] , it used to add/subtract time based on the timezone of the phone but it seems to be resolved now.


- (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.


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

NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];

If you need time stamp as a string.

time_t result = time(NULL);                
NSString *timeStampString = [@(result) stringValue];

If you want to store these time in a database or send it over the server...best is to use Unix timestamps. Here's a little snippet to get that:

+ (NSTimeInterval)getUTCFormateDate{

    NSDateComponents *comps = [[NSCalendar currentCalendar] 
                               components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit 
                               fromDate:[NSDate date]];
    [comps setHour:0];
    [comps setMinute:0];    
    [comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]];

    return [[[NSCalendar currentCalendar] dateFromComponents:comps] timeIntervalSince1970];  
}

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to nsdate

Get current date in Swift 3? How to get time (hour, minute, second) in Swift 3 using NSDate? Convert string to date in Swift Date Format in Swift How to convert string to date to string in Swift iOS? Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift Get day of week using NSDate Get UTC time and local time from NSDate object How can I convert string date to NSDate? How do you create a Swift Date object?

Examples related to unix-timestamp

Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds Getting current unixtimestamp using Moment.js How to parse unix timestamp to time.Time Go / golang time.Now().UnixNano() convert to milliseconds? Get current NSDate in timestamp format MYSQL query between two timestamps How to get current time with jQuery Convert unix time to readable date in pandas dataframe How to get the unix timestamp in C#