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

Hi Experts,

I have date something like 2012-01-31 and need to convert to 20120131

my $date = "2012-01-12"; print "date is := $date\n";

any suggestion please

Replies are listed 'Best First'.
Re: convert date format from YYYY-MM-DD to YYYYMMDD
by davido (Cardinal) on May 16, 2014 at 15:50 UTC

    Here are four solutions, starting from the trivial (and arguably most fragile).

    use feature 'say'; use DateTime::Format::Strptime qw(strptime strftime); use Time::Piece; my $raw_date = '2012-01-12'; # Using tr///; built into Perl. ( my $date = $raw_date ) =~ tr/-//d; say $date; # From Time::Piece; core since 5.10. $date = Time::Piece ->strptime( $raw_date, "%Y-%m-%d" ) ->ymd(''); say $date; # From DateTime::Format::Strptime; imported functions. $date = strftime( "%Y%m%d", strptime( "%Y-%m-%d", $raw_date ) ); say $date; # From DateTime::Format::Strptime; OO interface. $date = DateTime::Format::Strptime ->new( pattern => "%Y-%m-%d" ) ->parse_datetime($raw_date) ->ymd(''); say $date;

    Obviously tr/// is a built-in Perl operator. Time::Piece comes with Perl 5.10 and newer as a core module. DateTime::Format::Strptime is purely a CPAN module that fits into the vast DateTime ecosystem.


    Dave

      Hi Experts,

      Thanks all for the valuable inputs

      I am using $date =~ s/-//g;

      because I want to do conversion without using any perl modules

      Thank once again.

        That is a perfectly good approach if you’re certain the data will always match expectations. This is a poor assumption if you don’t know it for a fact though.

        The tr///d option is faster than s///g but it would only be something to really care about for huge datasets where the very small difference would add up.

        Lastly, I want to X without using any perl modules sounds like a good conclusion in this case but it’s one that you shouldn’t make in the general case unless this is pure hobby work you don’t care much about. Learning to use modules—there are good date ones in the core and plenty more available on the CPAN—and understanding the greater Perl ecosphere is what will make your future tasks easier, even trivial, and future employment and salary growth much more likely.

Re: convert date format from YYYY-MM-DD to YYYYMMDD
by Anonymous Monk on May 16, 2014 at 14:54 UTC
Re: convert date format from YYYY-MM-DD to YYYYMMDD
by flexvault (Monsignor) on May 16, 2014 at 14:55 UTC

    my $date = "2012-01-12"; $date =~ s/\-//g; print "date is : $date\n";

    Regards...Ed

    "Well done is better than well said." - Benjamin Franklin

Re: convert date format from YYYY-MM-DD to YYYYMMDD
by Lennotoecom (Pilgrim) on May 16, 2014 at 18:22 UTC
    also while
    $_ = "2012-01-12"; print $1 while /(\d)/g;
    haters gonna hate
    but TMTOWTDI, remember?