Perl格式日期

时间:2017-01-20 17:22:37

标签: perl date posix strftime

use Date::Calc qw(:all);
use Time::Piece;
use POSIX qw(strftime);
$a1 = '01.01.1963';
($year, $month, $day) = Decode_Date_US($a1);
print "$year $month $day\n";
$formatted = strftime('%m/%d/%Y',$month,$day,$year);
print "$formatted\n";

我正在尝试使用POSIX(strftime)以一致的格式格式化日期。我不确定输入格式是什么。我使用Decode_Date_US来提取相关的年,月,日信息。然后我尝试使用strftime以一致的方式格式化日期。我收到了以下错误 用法:test_dates.pl第60行的POSIX :: strftime(fmt,sec,min,hour,mday,mon,year,wday = -1,yday = -1,isdst = -1) < / p>

任何帮助都会受到赞赏。 &#34;使用Time :: Piece&#34;最终将用于对日期进行排序。

由于

2 个答案:

答案 0 :(得分:2)

只需使用Time::Piecestrptime

即可
#!/usr/bin/env perl
use strict;
use warnings;

use Time::Piece;

my $date = '01.01.1963';
my $timestamp = Time::Piece->strptime( $date, "%m.%d.%Y" );
print $timestamp -> strftime( "%m/%d/%Y")

但如果格式不一致,那么你就是失败者 - 对于初学者来说,有很多地方可以转换日/月订购,或者将年份表示为两位数(有时会与一个月或一天)。

它本质上含糊不清。你可以 - 充其量 - 通过抓取数字组和假设他们按照一致的顺序应用一些非常粗略的猜测。

E.g。

my ( $day, $month, $year ) = m/(\d{2}).*(\d{2}).*(\d{4})/; 

$timestamp = Time::Piece -> strptime ( "$year-$month-$day", "%Y-%m-%d" ); 

但是你会被10/11/12之类的日期绊倒,因为你根本无法知道哪个数字是哪个字段。您可以尝试通过eval strptime进行猜测,然后重试不同的格式,直到您得到一个 解码为有效的格式。

如你所示 - Decode_Date_US基本上这样做:

use strict;
use warnings;
use Date::Calc qw(:all);
use Time::Piece;
my $a1 = '01.01.1963';
my ($year, $month, $day) = Decode_Date_US($a1);
my $time = Time::Piece -> strptime("$year/$month/$day", "%Y/%m/%d");
print $time->strftime("%Y-%m-%d"),"\n";

另外 - use strict; use warnings;很好。

而且 - 其中一个 correct way to write dates。如果您要重新格式化,那么不明确的是最佳选择。

答案 1 :(得分:0)

我最终使用了DateTime模块的strftime函数,该函数可以处理1970年以前的日期。 &#34;崩溃&#34; -Perl命令行解释器已停止工作。如果它有帮助,我使用的是Windows机器和非常罕见的perl用户。

这对我有用

use Date::Calc qw(:all);
use DateTime;
$dateformat = "%m/%d/%Y";
($year, $month, $day) = Decode_Date_US($date);
$date = DateTime->new(
                  year=>$year,
                  month=>$month,
                  day=>$day,            
        );
$date = $date->strftime($dateformat);