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

I am trying to convert a string (date) to time (integer). The date string is in the format mm/dd/yyyy. What would you recommend I do?

Replies are listed 'Best First'.
Re: String (date) to time (integer)
by liverpole (Monsignor) on Jun 06, 2009 at 14:01 UTC
    Hi northwestdev,

    Use Time::Local for the function timelocal, which is the inverse of the builtin localtime.

    For example:

    use strict; use warnings; use Time::Local; my $date = "06/06/2009"; my ($m,$d,$y) = $date =~ m|(\d+)/(\d+)/(\d+)|; my $timet = timelocal(0, 0, 0, $d, $m-1, $y); print "Date '$date' => $timet\n" # Updated -- check the reverse my $ltime = localtime($timet); print "$timet => $ltime\n"; # Results: # Date '06/06/2009' => 1244260800 # 1244260800 => Sat Jun 6 00:00:00 2009

    Note that the first three arguments to timelocal above represent (respectively) the number of seconds, minutes, and hours; in your case they can be zero, as you're only interested in a one-day granularity.

    Update:  As Corion reminds me, the month passed to timelocal needs to be zero-based, not one-based the way humans represent dates.  Changing "$m" to "$m-1" in my code fixed this (thanks, Corion!).


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

      Actually not exactly:

      use strict; use Time::Local; for my $date ("06/06/2009",'01/30/09') { my ($m,$d,$y) = $date =~ m|(\d+)/(\d+)/(\d+)|; my $timet = timelocal(0, 0, 0, $d, $m, $y); print "Date '$date' => $timet\n"; print "localtime($timet): ", scalar localtime $timet, "\n"; } __END__ Date '06/06/2009' => 1246831200 localtime(1246831200): Mon Jul 6 00:00:00 2009 Day '30' out of range 1..28 at .pl line 6

      As the Time::Local documentation says:

      The value for the day of the month is the actual day (ie 1..31), while the month is the number of months since January (0..11).

      So you need to pass in $m-1 to adjust for that.

        Thank you. I am new to Perl, so I am not clear on how to decipher ("06/06/2009",'01/30/09').
      Personally, I tend to see Time::Local as "the hard way" (due in part to the 0-based/1-based issue) and prefer DateTime::Format::Strptime:
      #!/usr/bin/perl use strict; use warnings; use DateTime::Format::Strptime; my $date_parser = DateTime::Format::Strptime->new(pattern => '%D'); while (<DATA>) { print $date_parser->parse_datetime($_)->epoch, "\n"; } __DATA__ 06/06/2009 01/30/2009
      This example prints the epoch values for each date, as the OP said he wanted to convert them to an integer (and epoch is what the time function returns), but the DateTime suite also includes tools for displaying the date in pretty much whatever format you may want if epoch isn't what you're looking for.