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

Hello Monks. I know very little of Perl but I am trying to do something that you Monks will probably find very easy. I have a text date string of "Wednesday, May 20, 2009 2:09 PM" and I need to extract the $yday from it. Any help would be great. Thanks!

Replies are listed 'Best First'.
Re: Date String Conversion
by bichonfrise74 (Vicar) on Jul 28, 2009 at 00:13 UTC
    Is this what you are looking for?
    #!/usr/bin/perl use strict; use Date::Manip; my $old_date = 'Wednesday, May 20, 2009 2:09 PM'; my $new_date = UnixDate( $old_date, '%Y-%m-%d'); print $new_date;
      My date is a "text" string and I need to split up and rearrange if need be, to get the 9 element array returned by localtime. My ultimate goal is finding out the "Day of Year" or yearday(yday) of this timestamp.
Re: Date String Conversion
by Marshall (Canon) on Jul 28, 2009 at 00:16 UTC
    I have no idea what a $yday is!
    If you just need some tokens from this line like day and year:
    #!/usr/bin/perl -w use strict; my $string= "Wednesday, May 20, 2009 2:09 PM"; my ($day, $year) = (my @tokens = split(/[,\s]+/,$string))[0,3]; print "@tokens \n"; print "day =$day year =$year\n"; __END__ PRINTS: Wednesday May 20 2009 2:09 PM day =Wednesday year =2009
    Update: I'll add a bit more for you...split() is a function that parses a scalar value (here its just one line) and creates a list. In this case we "split" on any sequence of one (or more) comma's or space characters (\n\t\r\s\f). These go into the @tokens list. Perl has a very cool syntax called a "list slice", here I say give the first and fourth things which are the day and the year. "my @tokens =" is an intermediate variable that doesn't need to exist, I put it there so you could see the effect of the split.

    Give some examples of what need...short thing with couple of input lines and couple of output lines.

Re: Date String Conversion
by elTriberium (Friar) on Jul 28, 2009 at 02:08 UTC
    Here is a solution of just applying a regex to your String: I assume that you want the "20" as the day? Or what is $yday?
    my $date = 'Wednesday, May 20, 2009 2:09 PM'; my ($yday) = $date =~ /(\d+)/;
    The "20" are the first digits in this string, so I just captured the first 1+ digits in the regex.
Re: Date String Conversion
by Mr. Muskrat (Canon) on Jul 28, 2009 at 16:03 UTC

    Here are two untested solutions to give you a starting point.

    This first one uses DateTime.

    #!/usr/bin/perl use DateTime; use DateTime::Format::Flexible; my $date = 'Wednesday, May 20, 2009 2:09 PM'; my $dt = DateTime::Format::Flexible->parse_date_time( $date ); print 'The day of year is ', $dt->day_of_year(), "\n";

    The second uses Date::Calc.

    #!/usr/bin/perl use Date::Calc qw( Day_of_Year ); print 'The day of year is ', Day_of_Year(2009, 5, 20), "\n";