Because the order matters. If the regex checked for 'yy' before 'yyyy', then 'yyyy-mm-dd' would translate to '%y%y-%m-%d'.

use warnings; sub translate_date_format { my %tr = ( yyyy => "%Y", yy => "%y", mmmm => "%B", mmm => "%b", mm => "%m", m => "%e", ww => "%V", # or %U w => "%w", # or %u j => "%j", dddd => "%A", ddd => "%a", dd => "%d", d => "%e", HH => "%H", H => "%k", hh => "%I", h => "%i", MM => "%M", A => "%p", AM => "%p", PM => "%p", a => "%P", am => "%P", pm => "%P", SS => "%S", ZZZ => "%Z", ); my $str = shift; $str =~ s/(?<!%)$_/$tr{$_}/g for reverse sort keys %tr; return ($str); } ### Test ############################################################# +######### use POSIX; use Time::Piece; my @test = ( "yyyy-mm-dd", "d/mm/yy", "H:MM:SSAM", "HH:MM:SSpm", "mmm ddd, yy", "dddd, mmmm dd, yyyy HH:MM:SS", ); foreach (@test) { my $tdf = translate_date_format ($_); print "$_ => '$tdf'\n"; my $date = POSIX::strftime ($tdf, localtime ()); print " POSIX: $date\n"; my $t = localtime (); $date = $t->strftime ($tdf); print " Time::Piece: $date"; $date = $t->strptime ($date, $tdf); print " => $date\n"; }

I also see (using warnings) yet another reason never to use AM/PM :) :

HH:MM:SSpm => '%H:%M:%S%P' POSIX: 11:39:52am garbage at end of string in strptime: am at /pro/lib/perl5/site_perl/5 +.20.0/x86_64-linux-thread-multi-ld/Time/Piece.pm line 469. Time::Piece: 11:39:52am => Thu Jan 1 11:39:52 1970

Enjoy, Have FUN! H.Merijn

In reply to Re^4: Human-readable date format strings by Tux
in thread Human-readable date format strings by thewebsi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.