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

Hi Monks!
How could I get a date time format like this:
$datetime = $year.'-'.$mon.'-'.$mday.' '.$hour.':'.$min.':'.$sec.'.000 +';
Using "Date:Calc".
I have this for test:
#!/usr/bin/perl -w use strict; use CGI::Carp qw(fatalsToBrowser); use CGI qw(-oldstyle_urls :standard); use Date::Calc qw( Today Today_and_Now Date_to_Days Add_Delta_Days ); my $date = sprintf("%04d-%02d-%02d", (Date::Calc:Today())); # this one + does not work my $date2 = sprintf "%02d-%02d-%04d", (Date::Calc:Today())[1,2,0]; # i +t does not work as well my $date3 = sprintf "%04d-%02d-%02d",Today(); # this works, but I cant + get on the format I want. print $date; print $date2; print $date3; # this is the format I am trying to get using Date::Calc #$year.'-'.$mon.'-'.$mday.' '.$hour.':'.$min.':'.$sec.'.000';

How could I get that? Thanks for looking!

Replies are listed 'Best First'.
Re: Date Format Date::Calc
by PeterPeiGuo (Hermit) on Nov 19, 2010 at 19:51 UTC

    Use Today_and_Now() so you can get the hour/minute/second portion.

    use strict; use warnings; use Date::Calc qw(Today_and_Now); print sprintf("%4d-%2d-%2d %2d:%2d:%2d.000", Today_and_Now());

    Peter (Guo) Pei

      I think you've almost got it. I would suggest adjusting the format spec to pad the 2 digit fields with leading zeroes in the case of a single digit.
      print sprintf("%4d-%02d-%02d %02d:%02d:%02d.000", Today_and_Now());
      That way you get:
      2010-11-19 12:47:07.000 instead of... 2010-11-19 12:47: 7.000
Re: Date Format Date::Calc
by kcott (Archbishop) on Nov 19, 2010 at 20:13 UTC

    In the two you've listed as not working, you have a minor typo where you're missing a colon between Calc and Today. It should be: Date::Calc::Today.

    In the other one, you haven't shown your output which leaves me having to guess what the problem is:

    • The format you seem to want doesn't match the pattern you're using for sprintf.
    • The documentation for Date::Calc shows:
      ($year,$month,$day) = Today([$gmt]);
      so, clearly, that's not going to provide you with hours, minutes or seconds.

    -- Ken