Contributed by frankus
on Jun 08, 2000 at 15:53 UTC
Q&A
> dates and times
Answer: How do I find the difference in days between two dates, in a cool perl way? contributed by reptile If the dates are in epoch seconds, take the difference and divide it by the number of seconds in a day (which is 86400). Like so:
my $days_difference = int(($time1 - $time2) / 86400);
The int() there, by the way, chops off the decimal so you don't end up with something like 4.3231235. If you're curious, the remainder of that division is the number of seconds left after finding the number of days, so if you want "x days, x hours", you can do this next:
my $hours_left = int((($time1 - $time2) % 86400) / 3600);
That should give you an idea. If your dates aren't in epoch seconds, you'll either have to get them there somehow, or check out one of the Date::* modules.
| Answer: How do I find the difference in days between two dates, in a cool perl way? contributed by mojotoad Check out Time::Piece. This overides localtime(), gmtime(), arithmetic operations, and stringification so that date calculations are remarkably simple. For example:
use Time::Piece;
$before = Time::Piece->strptime("2001/01/01", "%Y/%m/%d");
$now = localtime;
$diff = $now - $before;
print int($diff->days), " days since $before\n";
| Answer: How do I find the difference in days between two dates, in a cool perl way? contributed by phenom Using Date::Calc:
#!/usr/bin/perl
use strict;
use warnings;
use Date::Calc qw/Delta_Days/;
my @first = (2001, 9, 12);
my @second = (2004, 3, 11);
my $dd = Delta_Days( @first, @second );
print "Difference in days: $dd\n";
| Answer: How do I find the difference in days between two dates, in a cool perl way? contributed by autarch Using DateTime (assuming $dt1 and $dt2 are DateTime objects):
my $duration = $dt1->delta_days($dt2);
print $duration->days;
|
Please (register and) log in if you wish to add an answer
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|