Reputation: 111
There has any simple ways how to calculate the number of days between two unix timestamps in perl, Ex, $time1= 1366601846 and $time2 = 1366431011, so the output is 2 days.
Even the differences between two unix time-stamps only two second, it should be consider as 1 day difference.
Thank before..
Upvotes: 2
Views: 2435
Reputation: 385655
In Europe/Paris, those two timestamps are
2013/04/20 06:10:11
2013/04/22 05:37:26
It's not clear what you want.
In Europe/Paris, the difference in times is one day, 23 hours and 15 minutes. Rounded up, that's 2 days. If this is what you want, you can use
use DateTime qw( );
my $dt1 = DateTime->from_epoch( epoch => 1366601846, time_zone => 'local' );
my $dt2 = DateTime->from_epoch( epoch => 1366431011, time_zone => 'local' );
my ($days, $minutes, $ns) = ($dt1 - $dt2)->in_units(qw( days minutes nanoseconds ));
++$days if $minutes || $ns;
print("$days\n");
In Europe/Paris, the difference in calendar dates in 2 days. If this is what you want, you can use
use DateTime qw( );
my $dt1 = DateTime->from_epoch( epoch => 1366601846, time_zone => 'local' );
my $dt2 = DateTime->from_epoch( epoch => 1366431011, time_zone => 'local' );
my $days = $dt1->delta_days($dt2)->in_units('days');
print("$days\n");
Dividing by 24*60*60 is not always going to work, whichever of the above you meant. In both case, the answer is dependent on the time zone you specify.
Upvotes: 4
Reputation: 91
To get a floating point number of the difference in days between two unix (epoch) dates, try this:
$days = abs ($time1 - $time2) / 86400;
Unix timestamps (or epoch timestamps) are a measure of the number of seconds since 1/1/1970 12AM UTC, so the raw difference is a difference in seconds. With 86400 being the total seconds in a day (60min * 60sec * 24hr), the result above is a difference in days.
However, this alone will leave you will a long floating-point number which you will probably want to trim down with either:
ceil() or floor() from the Posix module, or simply use printf or sprintf to change the variable value itself:
printf("%.0f", $days);
$days = sprintf("%.0f", $days);
Upvotes: -2