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

Hi,

I have the following code that takes a SQL datetime stamp and reformats it. The code works fine, however it seems a bit clunky, what other ways are there to achive the same result.

my $datetime = '2009-09-22 20::45::30'; my ($date,$time) = $datetime =~/(.+\s)(.+)/; $date =~ s/^\s+|\s$//; my @print_date = split ("-",$date); @print_date = reverse @print_date; print join ("/",@print_date) ."[$time]";
Format in = '2009-09-22 20::45::30'

Reformated out = 22/09/2009[20::45::30]

Thanks Skywalker

Replies are listed 'Best First'.
Re: DateTime Reformat
by ikegami (Patriarch) on Apr 22, 2009 at 18:45 UTC

    Since you aren't doing any date/time arithmetic or timezone changes, there's no need to treat the date/time as anything but text.

    my $datetime = '2009-09-22 20::45::30'; printf('%3$s/%2$s/%1$s[%4$s::%5$s::%6$s]'."\n", $datetime =~ /(\d+)/g );

    or

    my $datetime = '2009-09-22 20::45::30'; printf("%s/%s/%s[%s::%s::%s]\n", ( $datetime =~ /(\d+)/g )[2,1,0,3,4,5] );

    or

    my $datetime = '2009-09-22 20::45::30'; (my $print_date = $datetime) =~ s{(\d+)-(\d+)-(\d+) (.*)}{$3/$2/$1\[$4]}; print("$print_date\n");
Re: DateTime Reformat
by roboticus (Chancellor) on Apr 22, 2009 at 19:36 UTC
    skywalker:

    I normally let the database do that for me, as they often have the ability to do that kind of formatting. A couple examples:

    ORACLE:

    select BoringColumn, to_char(DateTimeColumn, 'YYYYMMDD') as TheDate from TABLE

    MS-SQL, Sybase:

    select BoringColumn, convert(varchar(8),DateTimeColumn,112) as TheDate from TABLE

    I don't use other database engines very often, so I'm not familiar with the syntax on any others...

    ...roboticus
Re: DateTime Reformat
by mikeraz (Friar) on Apr 22, 2009 at 18:20 UTC

    Consider:

    use Date::Parse; my $time = str2time($datetime); # $datetime from your example
    You then have a time object to use as needed.

    Be Appropriate && Follow Your Curiosity
      You'll need to do $datetime =~ s/::/:/g; first.
Re: DateTime Reformat
by DStaal (Chaplain) on Apr 22, 2009 at 18:29 UTC

    (Is it really '::'?)

    my $datetime = '2009-09-22 20::45::30'; $datetime =~ s|(/d{4})-(/d{2})-(/d{2}) ([[:digit:]:]+)|$3/$2/$1[$4]|; print $datetime;

    (Note: Code not tested.)

      Thats great, just what I was after, just need to add the open and close bracket around the time.

      thanks

        The brackets should be in there...

Re: DateTime Reformat
by bichonfrise74 (Vicar) on Apr 22, 2009 at 21:34 UTC
    Another possible solution...
    #!/usr/bin/perl use strict; my $old_dt = '2009-09-22 20::45::30'; my ($year, $mon, $day, $time) = $old_dt =~ /(\d{4})-(\d{2})-(\d{2})\s(.*)/; print "$day/$mon/${year}[$time]";