在perl脚本中格式化localtime()

时间:2012-04-03 16:05:59

标签: perl date

想知道如何将localtime()的输出格式化为年/月/日

我能够使用终端的'date'命令轻松完成,但我还需要计算以前的日期,我已经想出了如何在perl中做。

foreach my $i (0..7)
{
  my $date = localtime(time() - 60*60*24*$i);
  print "$i day(s) ago: $date\n";
}

打印出来:

0 day(s) ago: Tue Apr  3 12:01:13 2012
1 day(s) ago: Mon Apr  2 12:01:13 2012
2 day(s) ago: Sun Apr  1 12:01:13 2012
3 day(s) ago: Sat Mar 31 12:01:13 2012
4 day(s) ago: Fri Mar 30 12:01:13 2012
5 day(s) ago: Thu Mar 29 12:01:13 2012
6 day(s) ago: Wed Mar 28 12:01:13 2012
7 day(s) ago: Tue Mar 27 12:01:13 2012

4 个答案:

答案 0 :(得分:9)

以下是POSIX::strftime的示例:

use POSIX ();

my @local = ( localtime )[0..5];
foreach my $i ( 0..7 ) {
  my $date = POSIX::strftime( '%a %b %d %H:%M:%S %Y', @local);
  print "$i day(s) ago: $date\n";
  $local[3]--;
}

答案 1 :(得分:6)

如果您正在进行日期数学运算,请使用正确的模块。例如,DateTime

use DateTime;

my $date = DateTime->now;

foreach my $i ( 0 .. 10 ) {
    $date->subtract( days => 1 );
    say $date->ymd( '/' );
    }

答案 2 :(得分:3)

您可以使用POSIX模块中的POSIX::strftime

perl -mPOSIX -e 'printf POSIX::strftime("%Y/%m/%d",localtime)

答案 3 :(得分:3)

<强> 脚本:

#!/usr/bin/perl
use strict;

foreach my $i (0..7)
{
  my ($d, $m, $y) = (localtime(time() - 60*60*24*$i))[3,4,5];
  printf "%d day(s) ago: %d/%d/%d\n", $i, $y+1900, $m+1, $d;
}

<强> 输出:

0 day(s) ago: 2012/4/3
1 day(s) ago: 2012/4/2
2 day(s) ago: 2012/4/1
3 day(s) ago: 2012/3/31
4 day(s) ago: 2012/3/30
5 day(s) ago: 2012/3/29
6 day(s) ago: 2012/3/28
7 day(s) ago: 2012/3/27