Simple way to format date

前端 未结 4 1320
悲哀的现实
悲哀的现实 2021-01-22 12:54

I wrote a perl script to get datetime. It do work but I do wonder if there any easier way to format date as output.

#!/usr/bin/perl
use DateTime;

my $dt                 


        
4条回答
  •  渐次进展
    2021-01-22 13:50

    • First of all always use strict; and use warnings; at the start of your program and declare all your variables close to their first use. This applies especially if you are seeking help as it will find a lot of simple errors that aren't immediately obvious.

    It is best to use printf if you want to zero-pad any output. There is also no need to extract the date fields to separate variables. Is the output you have shown the one you ultimately want? This program does the same thing as the code you have posted.

    use strict;
    use warnings;
    
    use DateTime;
    
    my $myTimeStamp = DateTime->now->subtract( days => 1 );
    printf "--> %04d %02d %02d %02d\n", map $myTimeStamp->$_, qw/year month day hour/;
    

    OUTPUT

    --> 2012 02 28 12
    

提交回复
热议问题