in reply to Calculating between times

You can format your output, as another poster noted, with printf or sprintf; The code below does that. To find the difference between dates, you can use module Time::Local and it's function, timelocal().
#!/usr/bin/perl use strict; use warnings; use Time::Local; my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); printf("Today's date is: %02d.%02d.%02d\n", $mon+1, $mday, $year % 100); my $date = "12.25.03"; my ($m,$d,$y) = split /\./, $date; my $xmas_time = timelocal(0,0,0,$d,$m-1,$y); my $today = time; my $days_diff = int( ($today - $xmas_time) / (24*60*60) ); print "Difference is $days_diff days\n";
Chris

Replies are listed 'Best First'.
Re: Re: Calculating between times
by Anonymous Monk on Jan 09, 2004 at 05:24 UTC
    Your code worked great! The only problem with that was you had month.day.year . I tried changing the script to allow the new format but I can't seem to get it to work now. The script below prints these results:
    05.05.06 09.03.04 31.02.04 15.01.04 16.01.04 15.01.04 01.01.04 01.01.04 14.09.04 01.01.04 01.01.04 01.01.04 04.05.06 Day: 05 Month: 05 Year: 06 Day: 09 Month: 03 Year: 04 Software error: Day '31' out of range 1..29 at line 43
    Can you help me set it up so it works in this new format? it always dies on the third entry because the day is 31 when the error says it can only be 1..29.

    Thank you!

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); my $today = time; print "$today<br><br>"; foreach (keys %entries) { my ($date, $course, $location, $job_type, $contact) = split(/::/, $e +ntries{$_}); print "$date<br>"; } foreach (keys %entries) { my ($date, $course, $location, $job_type, $contact) = split(/::/, $e +ntries{$_}); my ($d,$m,$y) = split /\./, $date; my $saved_date = timelocal(0,0,0,$d,$m-1,$y); my $days_diff = int( ($today - $saved_date) / (24*60*60) ); print "Day: $d Month: $m Year: $y<br>"; }
      Last I checked, February, being the second month, doesn't in fact have 31 days. If you expected that to be March, then you have an off by one error and you should add one to the month column before attempting to format it.

      On the other, if you expect february to have 31 days, well, you have more problems then these perl ones!

        Whilst a 30 day February is not unheard of I agree, 31 is stretching it a bit too far :-)

        --
        Do not seek to follow in the footsteps of the wise. Seek what they sought. -Basho

        The thing is, I'm not testing the dates as they put them in. I have three pull down menus (day, month, year) where they select the according numbers. They have a 31 day limit and I don't do ANY checking on whether or not the month days actually exist.

        Unless you know of a perl snippet that could test to be sure these dates are valid, I'm not sure what to do.