检查时间戳是否在perl中以当前周为单位

时间:2018-02-05 13:25:26

标签: perl

我有一个包含键和时间戳的哈希值,如下所示。有没有办法找到哪些键有本周的时间戳。

my %hash = (
      'key1'  => '2018-01-17',
      'key2'  => '2018-02-05,2018-01-08',
      'key3'  => '2018-01-26' ,
      'key4'  => '2018-01-04',
      'key5'  => '2018-01-27,2018-02-06,2018-01-28'
    );

预期结果为:'key2'和'key5',当前一周的值为2018-02-05和2018-02-06。

2 个答案:

答案 0 :(得分:5)

我个人喜欢DateTime满足我所有的日期/时间需求,因为它是一个非常完整的解决方案。在下文中,我假设您的哈希值一致格式化(YYYY-MM-DD用逗号分隔,没有空格)。另请注意,这使用星期一作为一周的第一天,有关详细信息,请参阅DateTime truncate method

use warnings;
use strict;
use DateTime;
use DateTime::Format::Strptime;

my %hash = (
    'key1' => '2018-01-17',
    'key2' => '2018-02-05,2018-01-08',
    'key3' => '2018-01-26',
    'key4' => '2018-01-04',
    'key5' => '2018-01-27,2018-02-06,2018-01-28'
);

my $strp = DateTime::Format::Strptime->new( on_error=>'croak',
    pattern => '%Y-%m-%d', time_zone=>'floating' );

my $week_start = DateTime->now(time_zone=>'local')
    ->set_time_zone('floating')->truncate(to=>'week');
my $week_end   = $week_start->clone->add( days => 7 );

for my $key (sort keys %hash) {
    for my $date (split /,/, $hash{$key}) {
        my $dt = $strp->parse_datetime($date);
        # DateTime objects overload comparison operators
        if ( $week_start <= $dt && $dt < $week_end ) {
            print "$key\n";
        }
    }
}

答案 1 :(得分:4)

有很多方法可以做你想做的事。使用Time::Piece,我相信它是Perl 5.9.5的核心,你可以这样做:

use Time::Piece;

my %hash = (
  'key1' => '2018-01-17',
  'key2' => '2018-02-05,2018-01-08',
  'key3' => '2018-01-26' ,
  'key4' => '2018-01-04',
  'key5' => '2018-01-27,2018-02-06,2018-01-28'
);

my $current = localtime->strftime('%Y-%V');

foreach my $i (sort keys %hash) {
  foreach my $j (split /\s*,\s*/, $hash{$i}) {
    if( localtime->strptime($j, '%Y-%m-%d')->strftime('%Y-%V') eq $current ) {
      print 'Key: ', $i, ', date: ', $j, "\n";
    }
  }
}

它使用%V是ISO 8601周数的事实,它与年份相结合可以比较。

函数strptime将字符串转换为日期对象,然后strftime将日期对象转换为字符串。

输出:

Key: key2, date: 2018-02-05
Key: key5, date: 2018-02-06

函数strftime包含您可以使用的其他周定义:%U%V%W;例如,见here