Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Subtracting and Comparing Two Dates

by BaldPenguin (Friar)
on Jan 08, 2007 at 22:54 UTC ( [id://593639]=note: print w/replies, xml ) Need Help??


in reply to Subtracting and Comparing Two Dates

Try this, you have to use POSIX, but ...
use POSIX qw/difftime mktime/; my $now = time(); my @then = ($ARGV[0] =~ /^(\d{4})(\d{2})(\d{2})/); my $then = mktime(0,0,0,$then[2],$then[1]-1,$then[0]-1900); my $diff = difftime($now,$then); printf("%d days", int($diff/86400) ); printf(", %d hours", int( $diff%86400)/3600 ); printf(", %d minutes ", int( ($diff%86400)%3600 )/60 ); printf(", %d seconds \n", ( ($diff%86400)%3600 )%60 );
It may not be elegant, and could defintely benefit from some cleaner formatting like use of constants, but it gets the point across

Don
WHITEPAGES.COM | INC
Everything I've learned in life can be summed up in a small perl script!

Replies are listed 'Best First'.
Re^2: Subtracting and Comparing Two Dates
by ikegami (Patriarch) on Jan 09, 2007 at 03:01 UTC

    Your solution doesn't always give the right answer.

    Then Now Date::Calc BaldPenguin ---------- ------------------- ----------- ----------- 2005/08/01 2006/10/29 00:59:00 454 453.9993056 <- XXX 2005/08/01 2006/10/29 02:01:00 454 454.0840278 <- ok
    use strict; use warnings; use POSIX qw( difftime mktime strftime ); use Time::Local qw( timegm timelocal ); use Date::Calc qw( Delta_Days ); use constant ONE_DAY_IN_SECS => 24 * 60 * 60; sub baseline { my ($then_date_str, $now) = @_; my ($y1, $m1, $d1) = $then_date_str =~ /^(\d{4})(\d{2})(\d{2})\z/; my ($y2, $m2, $d2) = (localtime($now))[5,4,3]; $y2 += 1900; $m2 += 1; return Delta_Days($y1, $m1, $d1, $y2, $m2, $d2); } sub bald_penguin { my ($then_date_str, $now) = @_; my @then = $then_date_str =~ /^(\d{4})(\d{2})(\d{2})/; my $then = mktime(0,0,0,$then[2],$then[1]-1,$then[0]-1900); return difftime($now, $then) / ONE_DAY_IN_SECS; } { print("Then Now Date::Calc BaldPenguin\n" +); print("---------- ------------------- ----------- -----------\n" +); for ( [ '20050801', timelocal(0, 59, 0, 29, 10-1, 2006) ], [ '20050801', timelocal(0, 1, 2, 29, 10-1, 2006) ], ) { printf("%s %s %3d %3d %11.7f\n", do { my ($y, $m, $d) = $_->[0] =~ /^(\d{4})(\d{2})(\d{2})\z/; + sprintf("%04d/%02d/%02d", $y, $m, $d) }, strftime('%Y/%m/%d %H:%M:%S', localtime($_->[1])), baseline(@$_), bald_penguin(@$_), ); } }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://593639]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-19 16:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found