0

我正在使用 perl 来访问一个数据库,我从中获取 DD-MON-YYYY 格式的日期。我需要执行 2 个操作:

  1. 将此格式转换为 MM/DD/YYYY 格式。
  2. 将此日期与两个日期进行比较,以查看它是否在该时间范围内。

    我的 $chdate = '15-Feb-2013';

    子get_stats {

    my %map = ( 'Jan' => '01', 'Feb' => '02', 'Mar' => '03', 'Apr' => '04',
                'May' => '05', 'Jun' => '06', 'Jul' => '07', 'Aug' => '08',
                'Sep' => '09', 'Oct' => '10', 'Nov' => '11', 'Dec' => '12');
    
        $chdate =~ s/(..)-(...)-(....)/$map{$2}\/$1\/$3/;
        print "New date: $chdate";
    

    }

如何执行 (2) 操作?

我有一个旧版本的 Perl(没有 Time::Piece 模块),我没有更新的权限:)

4

3 回答 3

5

我建议您使用该Time::Piece模块。自 Perl5 v9.5 以来它一直是核心模块,因此可能不需要安装。

只需使用解码日期strptime并使用重新编码strftime

use strict;
use warnings;

use Time::Piece;

my $date = '28-jul-1986';

print Time::Piece->strptime($date, '%d-%b-%Y')->strftime('%m/%d/%Y');

输出

07/28/1986
于 2013-03-04T12:21:05.283 回答
1

If you convert your dates to Time::Piece object then you can compare them using the standard numeric comparison operators. So you could do something like this.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Piece;

my $start_date_str = '1-mar-2013';
my $end_date_str   = '31-mar-2013';
my $date_to_test_str = '4-mar-2013';

my $in_fmt  = '%d-%b-%Y';
my $out_fmt = '%m/%d/%y'; # Warning: Illogical format!

my $start_date_tp = Time::Piece->strptime(
  $start_date_str, $in_fmt
);
my $end_date_tp = Time::Piece->strptime(
  $end_date_str, $in_fmt
);
my $date_to_test_tp = Time::Piece->strptime(
  $date_to_test_str, $in_fmt
);

print $date_to_test_tp->strftime($out_fmt), ' is ';
unless ($start_date_tp <= $date_to_test_tp and
    $date_to_test_tp <= $end_date_tp) {
      print ' not ';
}
say 'between the two test dates';
于 2013-03-04T13:16:27.267 回答
-2

For (2) you can do this:

sub dateAsNumber # Arg mm/dd/yyyy - Converts to a number to be compared
{
   $_[0]=~m%(\d\d)/(\d\d)/(\d\d\d\d)%;
   return (($3 * 400 + $1) * 40 + $2);
}

$test = &dateAsNumber($testDateAsString);

if (&dateAsNumber($startDateAsString) < $test &&
    &dateAsNumber($endDateAsString) > $test)
{
   print "$test date is between $startDateAsString and $endDateAsString\n";
}
else
{
   print "$test date is NOT between $startDateAsString and $endDateAsString\n";
}
于 2013-03-08T02:23:42.283 回答