Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

后端 未结 9 1054
礼貌的吻别
礼貌的吻别 2021-01-30 02:30

When writing Perl scripts I frequently find the need to obtain the current time represented as a string formatted as YYYY-mm-dd HH:MM:SS (say 2009-11-29 14:28

9条回答
  •  无人共我
    2021-01-30 02:55

    Why not use the DateTime module to do the dirty work for you? It's easy to write and remember!

    use strict;
    use warnings;
    use DateTime;
    
    my $dt   = DateTime->now;   # Stores current date and time as datetime object
    my $date = $dt->ymd;   # Retrieves date as a string in 'yyyy-mm-dd' format
    my $time = $dt->hms;   # Retrieves time as a string in 'hh:mm:ss' format
    
    my $wanted = "$date $time";   # creates 'yyyy-mm-dd hh:mm:ss' string
    print $wanted;
    

    Once you know what's going on, you can get rid of the temps and save a few lines of code:

    use strict;
    use warnings;
    use DateTime;
    
    my $dt = DateTime->now;
    print join ' ', $dt->ymd, $dt->hms;
    

提交回复
热议问题