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

Hey Everyone, OK here is my issue today: I need to convert this time format "04/18/00 11:10 AM" to this time format "Tue Sep 25 15:25:43 2001" so that I may get this format "1001449543" (unix time). How would you all suggest I hand this?? I am confused on what to do now...

-----------------------
Billy S.
Slinar Hardtail - Guildless
Datal Ephialtes - Guildless
RallosZek.Net Admin/WebMaster
Aerynth.Net Admin/WebMaster

perl -e '$cat = "cat"; if ($cat =~ /\143\x61\x74/) { print "Its a cat! +\n"; } else { print "Thats a dog\n"; } print "\n";'

Replies are listed 'Best First'.
Re: Time Conversion Help
by gryphon (Abbot) on Sep 26, 2001 at 00:59 UTC

    Greetings LostS,

    Well, I just found a better way. As you'd expect, there's a module that does exactly this very thing:

    #!/usr/bin/perl -w use strict; use Time::ParseDate; my $unix_time = parsedate('04/18/00 11:10 AM'); my $normal_time = localtime($unix_time); print "$unix_time == $normal_time\n";

    The advantage here over my previous posted code is that here the date/time format is not so strict. Time::ParseDate allows for a fairly wide range of date/time formats. It'll also do all the conversion for you.

    -gryphon
    code('Perl') || die;

Re: Time Conversion Help
by gryphon (Abbot) on Sep 26, 2001 at 00:47 UTC

    Greetings LostS,

    The following isn't really a super-cool way to do this, but it seems to work in the test cases I've run. I'm sure merlyn or others could come up with something far smaller and better. But here it is:

    #!/usr/bin/perl -w use strict; use Time::Local; my $original_time = '04/18/00 11:10 AM'; my ($mon, $mday, $year, $hours, $min, $mer) = split(/ |\/|:/, $origina +l_time); $hours += 12 if ($mer eq 'PM'); if ($year < 50) { $year += 2000; } else { $year += 1900; } my $unix_time = timelocal(0, $min, $hours, $mday, $mon - 1, $year); my $normal_time = localtime($unix_time); print "$unix_time == $normal_time\n";

    -gryphon
    code('Perl') || die;

      That works beautifully :) THANK YOU soo much
      Now to finish up this web site converter :)


      -----------------------
      Billy S.
      Slinar Hardtail - Guildless
      Datal Ephialtes - Guildless
      RallosZek.Net Admin/WebMaster
      Aerynth.Net Admin/WebMaster

      perl -e '$cat = "cat"; if ($cat =~ /\143\x61\x74/) { print "Its a cat! +\n"; } else { print "Thats a dog\n"; } print "\n";'
Re: Time Conversion Help
by Rhandom (Curate) on Sep 26, 2001 at 01:56 UTC
    There is also the module Date::Parse that can help. I don't know its relation to Time::ParseDate but I have used it to parse email dates fairly handily.

    Usage is as follows:

    use Date::Parse qw(str2time); my $unix_time = str2time("Tue Sep 25 15:25:43 2001"); print "$unix_time\n"; $unix_time = str2time("04/18/00 11:10 AM"); print "$unix_time\n";


    my @a=qw(random brilliant braindead); print $a[rand(@a)];