【问题标题】:How to implement an addate utility in perl?如何在 perl 中实现 addate 实用程序?
【发布时间】:2012-09-02 06:37:59
【问题描述】:

我没有使用 perl 的经验,我需要创建一个实用程序,它会在添加偏移量后打印日期,格式字符串是 strftime 格式字符串。

格式:./adddate number_of_days [format_string]

示例:./adddate -1 "%a, %b %d" # 打印昨天的日期

【问题讨论】:

  • 使用DateTime::Format::Strptime解析传入的时间戳,使用DateTime对其进行操作。
  • Date::Calc 是另一种选择。
  • 所以你有日期和偏移量,并会得到特定 strftime 格式的结果(日期+偏移量)?
  • 是的,这就是我需要的,(日期+偏移)在特定的 strftime 格式

标签: perl date strftime


【解决方案1】:

经过一番研究,我能够编写代码:

#!/usr/bin/perl 
use DateTime;
$offset = $ARGV[0];
$format = $ARGV[1];
$dt = DateTime->now();
$dt->add( days => $offset );
print $dt->strftime($format)."\n";

【讨论】:

    【解决方案2】:

    要添加天数,只需以细分形式增加时间的tm_mday 字段(由localtime 返回)。然后,mktime-localtime 往返将重新规范化它,考虑月或年的翻转。

    use strict;
    use feature qw( say );
    use POSIX qw( mktime strftime );
    
    my $offset = $ARGV[0];
    my $format = $ARGV[1];
    
    my @t = localtime;
    $t[3] += $offset;  # tm_mday field
    
    say strftime( $format, localtime mktime @t );
    

    所有核心模块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-22
      • 2011-08-09
      • 1970-01-01
      • 2012-05-16
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多