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

后端 未结 9 1212
礼貌的吻别
礼貌的吻别 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:43

    Use strftime in the standard POSIX module. The arguments to strftime in Perl’s binding were designed to align with the return values from localtime and gmtime. Compare

    strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)
    

    with

    my          ($sec,$min,$hour,$mday,$mon,$year,$wday,     $yday,     $isdst) = gmtime(time);
    

    Example command-line use is

    $ perl -MPOSIX -le 'print strftime "%F %T", localtime $^T'
    

    or from a source file as in

    use POSIX;
    
    print strftime "%F %T", localtime time;
    

    Some systems do not support the %F and %T shorthands, so you will have to be explicit with

    print strftime "%Y-%m-%d %H:%M:%S", localtime time;
    

    or

    print strftime "%Y-%m-%d %H:%M:%S", gmtime time;
    

    Note that time returns the current time when called whereas $^T is fixed to the time when your program started. With gmtime, the return value is the current time in GMT. Retrieve time in your local timezone with localtime.

提交回复
热议问题