How to display 4/25/10 to 2010-25-04?

前端 未结 4 1358
日久生厌
日久生厌 2021-01-24 06:37
my$str= \'4/25/10\';
my$sr = join(\' \',split (/\\//,$str));
#my$s = sprintf \'%3$d %2$d %1$d\',$srt;
print$sr,\"\\n\";

output:

<
相关标签:
4条回答
  • 2021-01-24 06:46

    Well, a braindead solution might be:

    my @date = split( /\//,$str)
    printf("%04d-%02d-%02d", $date[2] + 2000, $date[1], $date[0]);
    

    You could write something a little more self-documenting by highlighting what you expect to be year, month and day like so:

    my ($day, $month, $year) = split /\//, $str;
    printf("%04d-%02d-%02d", $year + 2000, $month, $day);
    
    0 讨论(0)
  • 2021-01-24 06:48
    use DateTime::Format::Strptime;
    my $strp = DateTime::Format::Strptime->new(
        pattern   => '%m/%d/%y',
        locale    => 'en_US'
    );
    my $dt = $strp->parse_datetime('4/25/10');
    print $dt->strftime('%Y-%d-%m'), "\n";
    

    Gives:

    2010-25-04
    
    0 讨论(0)
  • 2021-01-24 06:51

    You're not that far off.

    Instead of splitting and joining in a single operation, you can keep individual variables to handle the data better:

    my ($d,$m,$y) = split /\//, $str;
    

    Then you can format it in most any way you please, for example:

    printf "20%02d-%02d-%02d\n", $y, $d, $m;
    

    A few notes, though:

    • I won't comment about the source format, but the format you're converting to doesn't make a lot of sense. You'd probably be better using ISO-8601: 2010-04-25.
    • Obviously, this way of doing only works up to year 2099.
    • For anything more serious, you'd be better off delegating this kind of work to date handling modules. See for example this question for parsing and this question for formatting
    0 讨论(0)
  • 2021-01-24 07:01

    No need to do to DateTime for this. Time::Piece has been included with the Perl core distribution for years.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use 5.010;
    
    use Time::Piece;
    
    my $date = '4/25/10';
    
    my $date_tp = Time::Piece->strptime($date, '%m/%d/%y');
    
    say $date_tp->strftime('%Y-%m-%d');
    
    0 讨论(0)
提交回复
热议问题