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

#!/usr/bin/perl use Date::Format; my $date = '20080501'; print time2str("%Y-%m-%d", $date), "\n";
The output is
1970-08-21
So How can I get the date in the format 2008-05-01

Replies are listed 'Best First'.
Re: Convert date
by Corion (Patriarch) on Jul 15, 2009 at 07:13 UTC

    The time passed into time2str is supposed to be the number of seconds since 01.01.1970 ("epoch"), and not a string describing a year+month+date. So you'll have to first parse the date into its year,month,day parts, and then possibly use Time::Local to find the epoch time corresponding to that time.

Re: Convert date
by ropey (Hermit) on Jul 15, 2009 at 08:22 UTC

    If you just need to convert the date without any validation, why not do

    my $date = '20080501'; $date =~ s/^(\d{4})(\d{2})(\d{2})$/$1-$2-$3/;
      Why does the line print Use of uninitialized value in substitution (s///) How to avoid it

        The following code does not print any warning for me:

        >perl -wle "my $date='20080501'; $date =~ s/^(\d{4})(\d{2})(\d{2})$/$1 +-$2-$3/;print $date" 2008-05-01

        So the problem must be with your other code and/or how you're using it. My guess is that $date in your case is not defined. Print out $date before trying a substitution on it:

        print "I think \$date is [$date]\n";
Re: Convert date
by Anonymous Monk on Jul 15, 2009 at 07:15 UTC
      Convert the string '20080501' to '2008-05-01'
Re: Convert date
by ambrus (Abbot) on Jul 15, 2009 at 16:21 UTC
    use Date::Manip; my $date = "20080501"; print UnixDate($date, "%Y-%m-%d\n");