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

Hi everyone
My problem is probably quite simple to solve for u wise perlmonks... Anyway, I have dates in yyyymmdd format which I want to format to yyyy-mm-dd. How do I do this?:)
thanks

Replies are listed 'Best First'.
Re: formatting dates
by Abigail-II (Bishop) on Oct 06, 2003 at 11:46 UTC
    $date = "YYYYMMDD"; $date =~ s/(.{4})(.{2})(.{2})/$1-$2-$3/; # Yeah, you can save a f +ew chars. But I find this clearer.

    Abigail

Re: formatting dates
by antirice (Priest) on Oct 06, 2003 at 13:00 UTC

    In the spirit of TIMTOWTDI:

    $date = "20031006"; $date = join "-",unpack("a4a2a2",$date);

    Of course, I'd probably say doing it with the regex would be preferred.

    antirice    
    The first rule of Perl club is - use Perl
    The
    ith rule of Perl club is - follow rule i - 1 for i > 1

Re: formatting dates
by Albannach (Monsignor) on Oct 06, 2003 at 13:19 UTC
    I would use the regex by reflex, I think the unpack is pretty cool, and for yet more TIMTOWTDI, this is just ammo for those that like to benchmark substr against regexen:
    $date = 'yyyymmdd'; substr($date,$_,0) = '-' for(6,4);
    Update: stupid typo fixed

    --
    I'd like to be able to assign to an luser

Re: formatting dates
by jeffa (Bishop) on Oct 06, 2003 at 13:06 UTC
Re: formatting dates
by Roger (Parson) on Oct 06, 2003 at 12:06 UTC
    I was doing almost the samething earlier today at work, where I formatted date to yyyy/mm/dd instead. The following code should format the date to your specification.
    $date =~ s/(\d{4})(\d{2})(\d{2})/$1-$2-$3/;
Re: formatting dates (idempotent)
by tye (Sage) on Oct 06, 2003 at 18:50 UTC

    Here is a way that works on dates with or without punctuation (:

    $date = sprintf "%d%d-%02d-%02d", $date =~ /(\d\d?)/g

                    - tye
Re: formatting dates
by Aristotle (Chancellor) on Oct 06, 2003 at 19:35 UTC
    For the sake of completeness, an ultra flexible solution:
    use Time::Local; use POSIX qw(strftime); my ($Y, $M, $D) = unpack "A4 A2 A2", $date; $M--; my $newdate = strftime('%Y-%m-%d', gmtime timegm(0, 0, 0, $D, $M, $Y)) +;
    Of course for just changing the naming scheme on a few files or something like that, it does a ridiculous amount of work and I'd stick with a join.

    Makeshifts last the longest.