http://www.perlmonks.org?node_id=673547

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

Hi,

Can anyone tell me how to convert the current date into YYYYMMDD format?

Thanks,
Lou

Replies are listed 'Best First'.
Re: Date YYYYMMDD format
by jwkrahn (Abbot) on Mar 11, 2008 at 17:09 UTC
    use POSIX 'strftime'; my $date = strftime '%Y%m%d', localtime;
      How to grep the time format in the log file without using the hhmmss format?
Re: Date YYYYMMDD format
by grinder (Bishop) on Mar 11, 2008 at 19:21 UTC

    Here's one I like:

    my $ymd = sub{sprintf '%04d%02d%02d', $_[5]+1900, $_[4]+1, $_[3]}->(localtime);

    The interesting thing about it is the dataflow aspect, how you take a stream of variables and modify them on the way to their destination. Having this particular tool in you toolbox can come in handy from time to time.

    • another intruder with the mooring in the heart of the Perl

Re: Date YYYYMMDD format
by samtregar (Abbot) on Mar 11, 2008 at 17:06 UTC
    use DateTime; print DateTime->now(time_zone => "local")->ymd('');

    -sam

Re: Date YYYYMMDD format
by gamache (Friar) on Mar 11, 2008 at 16:45 UTC
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(t +ime); my $yyyymmdd = sprintf "%.4d%.2d%.2d", $year+1900, $mon+1, $mday;
    Also see localtime.
Re: Date YYYYMMDD format
by toolic (Bishop) on Mar 11, 2008 at 16:43 UTC
    #!/usr/bin/env perl use warnings; use strict; my($day, $month, $year) = (localtime)[3,4,5]; $month = sprintf '%02d', $month+1; $day = sprintf '%02d', $day; print $year+1900, $month, $day, "\n";

    Prints:

    20080311
Re: Date YYYYMMDD format
by apl (Monsignor) on Mar 11, 2008 at 17:38 UTC