in reply to convert date format from YYYY-MM-DD to YYYYMMDD

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

Replies are listed 'Best First'.
Re^2: convert date format from YYYY-MM-DD to YYYYMMDD
by Perlseeker_1 (Acolyte) on May 16, 2014 at 16:05 UTC
    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.