本文介绍了快速到达YYYY-mm-dd HH:MM:SS在Perl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写Perl脚本时,我经常发现需要获得当前时间的格式,格式为 YYYY-mm-dd HH:MM:SS (说 2009-11-29 14:28:29 )。

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:29).

在这样做的时候,我发现自己采取这个相当麻烦的路径:

In doing this I find myself taking this quite cumbersome path:


  • man perlfunc

  • / localtime 搜索本地时间 - 重复五次( / + \\\
    )到达联机帮助页的相关部分

  • 复制字符串($ sec,$ min,$ hour,$ mday,$ mon,$ year ,$ wday,$ yday,$ isdst)= localtime(time); 从联机帮助页到我的脚本。

  • 尝试使用我的$ now = sprintf(%04d-%02d-%02d%02d:%02d:%02d,$ year,$ mon,$ mday,$ hour,$ min,$ sec);

  • 记住gotcha#1:必须添加1900到$ year才能获得当年。

  • 尝试使用 my $ now = sprintf(%04d-%02d-%02d%02d:%02d:%02d,$ year + 1900,$ mon,$ mday,$ hour,$ min,$ sec); / li>
  • 记忆呃呵呵#2:必须添加1到$ mon才能获得当前月份。

  • 尝试使用 my $ now = sprintf(%04d-%02d-%02d %02d:%02d:%02d,$ year + 1900,$ mon + 1,$ mday,$ hour,$ min,$ sec);


  • man perlfunc
  • /localtime to search for localtime - repeat five times (/ + \n) to reach the relevant section of the manpage
  • Copy the string ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); from the manpage to my script.
  • Try with my $now = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year, $mon, $mday, $hour, $min, $sec);
  • Remember gotcha #1: Must add 1900 to $year to get current year.
  • Try with my $now = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year+1900, $mon, $mday, $hour, $min, $sec);
  • Remember gotcha #2: Must add 1 to $mon to get current month.
  • Try with my $now = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year+1900, $mon+1, $mday, $hour, $min, $sec);
  • Seems ok. Done!

虽然上述过程的工作原理远远不够。我确定有一个更聪明的方式,所以我的问题只是:

While the process outlined above works it is far from optimal. I'm sure there is a smarter way, so my question is simply:

获得 YYYY-在Perl当前日期/时间的mm-dd HH:MM:SS

其中easy包含易于写入和易于记忆。

Where "easy" encompasses both "easy-to-write" and "easy-to-remember".

推荐答案

使用 strftime 在标准 POSIX module:

Use strftime in the standard POSIX module:

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

Perl绑定中 strftime 的参数设计为与来自 localtime gmtime 的返回值对齐。

The arguments to strftime in Perl's binding were designed to align with the return values from localtime and gmtime.

这篇关于快速到达YYYY-mm-dd HH:MM:SS在Perl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 02:52