使用 perl Date::Manip 将一种日期格式转换为另一种格式
Convert one format of date to another format using perl Date::Manip
我正在尝试将传入日期转换为另一种格式,下面是我编写的代码。
#!/usr/bin/perl
#
use POSIX qw(strftime);
use Date::Manip;
my $string = "Run started at 12:01:48 PM on Aug 19 2016 ";
my @array = split(' ',$string);
$string = "12:01:48 PM Aug 19, 2016";
$unix_time = UnixDate( ParseDate($string), "%s" );
#print $unix_time;
my $datestring = strftime "%a %b %e %H:%M:%S %Y", gmtime($unix_time);
printf("date and time - $datestring\n");
我想要 Fri Aug 19 12:01:48 2016
中的输出,但没有考虑到 PM,你能帮我吗?
您是否考虑过使用 Time::Piece 而不是 Date::Manip?它是标准 Perl 发行版的一部分(自 Perl 5.10 起),通常被认为远远优于 Date::Manip.
您需要使用 strptime()
(字符串解析时间)将您的字符串转换为 Time::Piece 对象,然后使用 strftime()
(字符串格式化时间)将您的对象转换为字符串按照要求的格式。
#!/usr/bin/perl
use strict;
use warnings;
# We use modern Perl - specifically say()
use 5.010;
use Time::Piece;
my $string = '12:01:48 PM Aug 19, 2016';
my $tp = Time::Piece->strptime($string, '%H:%M:%S %p %b %d, %Y');
say $tp->strftime('%a %b %e %H:%M:%S %Y');
更新: 回答你原来的问题,我想你被时区搞得焦头烂额了。 ParseDate()
似乎假定该字符串在本地时区 - 但您正在使用 gmtime()
生成新的日期字符串。如果将其切换为 localtime()
,您将获得所需的答案。
我正在尝试将传入日期转换为另一种格式,下面是我编写的代码。
#!/usr/bin/perl
#
use POSIX qw(strftime);
use Date::Manip;
my $string = "Run started at 12:01:48 PM on Aug 19 2016 ";
my @array = split(' ',$string);
$string = "12:01:48 PM Aug 19, 2016";
$unix_time = UnixDate( ParseDate($string), "%s" );
#print $unix_time;
my $datestring = strftime "%a %b %e %H:%M:%S %Y", gmtime($unix_time);
printf("date and time - $datestring\n");
我想要 Fri Aug 19 12:01:48 2016
中的输出,但没有考虑到 PM,你能帮我吗?
您是否考虑过使用 Time::Piece 而不是 Date::Manip?它是标准 Perl 发行版的一部分(自 Perl 5.10 起),通常被认为远远优于 Date::Manip.
您需要使用 strptime()
(字符串解析时间)将您的字符串转换为 Time::Piece 对象,然后使用 strftime()
(字符串格式化时间)将您的对象转换为字符串按照要求的格式。
#!/usr/bin/perl
use strict;
use warnings;
# We use modern Perl - specifically say()
use 5.010;
use Time::Piece;
my $string = '12:01:48 PM Aug 19, 2016';
my $tp = Time::Piece->strptime($string, '%H:%M:%S %p %b %d, %Y');
say $tp->strftime('%a %b %e %H:%M:%S %Y');
更新: 回答你原来的问题,我想你被时区搞得焦头烂额了。 ParseDate()
似乎假定该字符串在本地时区 - 但您正在使用 gmtime()
生成新的日期字符串。如果将其切换为 localtime()
,您将获得所需的答案。