perl - formatting DateTime output

前端 未结 3 1463
北荒
北荒 2021-01-05 02:13

How do I convert my return using DateTime from:

This is my date:2011-11-26T20:11:06 to This is my date:20111126

Using this existin

相关标签:
3条回答
  • 2021-01-05 02:31

    There are about a dozen ways to process dates in Perl. However, if you know the format of the date string, there maybe no reason to call a datetime module:

    $dt3 =~ /^(\d+)-(\d+)-(\d+)/;
    print "This is my date:${1}${2}${3}\n";
    

    I'm not familiar with DateTime, but I'd be surprised if there wasn't a way to format the data when you display it.

    I personally prefer Time::Piece and Time::Seconds for these things. These modules have been part of the standard Perl installation since 5.10. Plus, I find the interface to be fairly simple and clean.

    use Time::Piece;
    use Time::Seconds;
    
    my $time = localtime;
    $time -= ONE_DAY;
    
    print "This is my date:" . $time->ymd("");
    

    For some reason, you can't say $time = localtime - ONE_DAY; on the same line. I guess you need to create the Time::Piece object first before you can manipulating them with the Time::Second constants.

    0 讨论(0)
  • 2021-01-05 02:47

    ymd is the simplest:

    print "This is my date: ", $dt3->ymd(''), "\n";
    

    strftime is more general purpose:

    print "This is my date: ", $dt3->strftime('%Y%m%d'), "\n";
    

    There are also specific (e.g. DateTime::Format::Atom) and general (e.g. DateTime::Format::Strptime) formatting helper tools you can use:

    use DateTime::Format::Strptime qw( );
    my $format = DateTime::Format::Strptime->new( pattern => '%Y%m%d' );
    print "This is my date: ", $format->format_datetime($dt3), "\n";
    

    PS — Your code will give the date in or near England, not the date where you are located. For that, you want

    my $dt3 = DateTime->now(time_zone => 'local');
    

    or the more appropriate

    my $dt3 = DateTime->today(time_zone => 'local');
    
    0 讨论(0)
  • 2021-01-05 02:51

    Just add ->ymd("") on the second line. The parameter "" is the separator, which you chose to be an empty string.

    use DateTime qw();
    my $dt3 = DateTime->now->subtract(days => 1)->ymd("");
    print "This is my date:$dt3\n"
    
    0 讨论(0)
提交回复
热议问题