Convert Unix TimeStamp to NSDate & calculate difference between 2 dates

today, i’ve faced up with unix timestamp and converting it to NSDATE task.

for example, we have date in ‘1226357333′ format, how should we convert it on iphone?

answer is pretty simple :)

NSTimeInterval unixDate = 1226357333;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:unixDate];

what we need is just place our magic number into NSTimerInterval and then convert it through dateWithTimeIntervalSince1970 function.

okay, the next thing is to calculate how much time did pass from one date to another

for example we have timestamp at 2008-11-11 00:48:53 +0200

and right now is 2009-03-20 12:31:08 +0200

how should we calculate the difference?

that is quite simple too :)

NSTimeInterval unixDate = 1226357333;
 
NSDate *date = [NSDate dateWithTimeIntervalSince1970:unixDate];
NSDate *currentDate = [NSDate date];
 
NSTimeInterval difference = 
                      [currentDate timeIntervalSinceDate:date] / 86400;
NSLog(@"Days difference: %f", difference);

as you see, we’ve used date variable with converted unix stamp and currentDate variable.

then we’ve calculated the difference through timeIntervalSinceDate function

but here is a thing, timeIntervalSinceDate return seconds to us, so we need convert them to suitable format, you may divide difference at 60 - mins, 3600 - hours, 86400 - days etc.

Trackback URL

,

One Comment on "Convert Unix TimeStamp to NSDate & calculate difference between 2 dates"

  1. alex
    Ondrej
    19/02/2010 at 6:36 am Permalink

    Thanks for that mate :)

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Subscribe to Comments