Today's Date in Perl in MM/DD/YYYY format

后端 未结 7 1166
醉酒成梦
醉酒成梦 2020-12-24 11:18

I\'m working on a Perl program at work and stuck on (what I think is) a trivial problem. I simply need to build a string in the format \'06/13/2012\' (always 10 characters,

相关标签:
7条回答
  • 2020-12-24 11:30
    use DateTime qw();
    DateTime->now->strftime('%m/%d/%Y')   
    

    expression returns 06/13/2012

    0 讨论(0)
  • 2020-12-24 11:31

    Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)

    use strict;
    use warnings;
    use Date::Calc qw();
    my ($y, $m, $d) = Date::Calc::Today();
    my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
    print $ddmmyyyy . "\n";
    

    This gives you:

    14.05.2014

    0 讨论(0)
  • 2020-12-24 11:38
    use Time::Piece;
    ...
    my $t = localtime;
    print $t->mdy("/");# 02/29/2000
    
    0 讨论(0)
  • 2020-12-24 11:39

    You can use Time::Piece, which shouldn't need installing as it is a core module and has been distributed with Perl 5 since version 10.

    use Time::Piece;
    
    my $date = localtime->strftime('%m/%d/%Y');
    print $date;
    

    output

    06/13/2012
    


    Update

    You may prefer to use the dmy method, which takes a single parameter which is the separator to be used between the fields of the result, and avoids having to specify a full date/time format

    my $date = localtime->dmy('/');
    

    This produces an identical result to that of my original solution

    0 讨论(0)
  • 2020-12-24 11:40

    You can do it fast, only using one POSIX function. If you have bunch of tasks with dates, see the module DateTime.

    use POSIX qw(strftime);
    
    my $date = strftime "%m/%d/%Y", localtime;
    print $date;
    
    0 讨论(0)
  • 2020-12-24 11:47

    If you like doing things the hard way:

    my (undef,undef,undef,$mday,$mon,$year) = localtime;
    $year = $year+1900;
    $mon += 1;
    if (length($mon)  == 1) {$mon = "0$mon";}
    if (length($mday) == 1) {$mday = "0$mday";}
    my $today = "$mon/$mday/$year";
    
    0 讨论(0)
提交回复
热议问题