Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I am working on a program and I have to calculate if the date (stored) coming from the database is older than today's date. I have this sample code that works, my question is if this is an efficient way of doing this, here the code I have:
#!/usr/bin/perl use strict; use CGI; use CGI::Carp qw/fatalsToBrowser warningsToBrowser/; use Date::Calc qw(Delta_Days); use Date::Calc qw[Add_Delta_Days Today]; my $q = new CGI; print $q->header; my $got_date = "1/1/2010"; # this is only to show, but this is the for +mat of the date I will be getting from the db table. my ($got_month,$got_day,$got_year) = split /\//, $got_date; # split da +te in 3 parts with / as delimiter my ($year, $month, $day) = Today(); my @today = ($year, $month, $day); my @date_got = ($got_year, $got_month, $got_day); my $difference = Delta_Days(@date_got, @today); print "There were $difference days between Today and Stored Date\n\n";


Thanks for the Help!

Replies are listed 'Best First'.
Re: Subtracting certain number of days from current date.
by stefbv (Priest) on Feb 03, 2010 at 20:17 UTC

    I don't know about the efficiency but here is how i would write it, (ignoring the CGI part).

    use strict; use warnings; use Date::Calc qw(Delta_Days Decode_Date_US Today); my $date1 = '1/1/2010'; # Supose date is in US format my ( $year , $month , $day ) = Today(); my ( $year1, $month1, $day1 ) = Decode_Date_US($date1); my $dd = Delta_Days( $year1, $month1, $day1, $year, $month, $day ); print "There were $dd days between Today and $date1\n";
      Unless you have a later use for the parts of the dates, why not:
      my $dd = Delta_Days( Decode_Date_US($date1), Today() );
Re: Subtracting certain number of days from current date.
by ahmad (Hermit) on Feb 04, 2010 at 00:12 UTC

    If you are working in database then you could use some kind of built-in function in your query (few people said it would be faster) -- never done the benchmarking myself.

    For example in mysql you can do it this way.

    SELECT *,DATEDIFF(NOW(),`YourDateField`) AS `DiffDate` FROM `table` WH +ERE `x` = 'y' this will return an additional column for every row containing the dat +e difference between the current date and the date stored in the data +base.
Re: Subtracting certain number of days from current date.
by ikegami (Patriarch) on Feb 03, 2010 at 20:03 UTC
    Do you have any reason to think it's not efficient?
      Maybe how the "split" is in the date coming from the DB? What if the format of the date changes?