我用过 当地时间 Perl 中的函数获取当前日期和时间,但需要解析现有日期。我有以下格式的 GMT 日期:“20090103 12:00”我想将其解析为我可以使用的日期对象,然后将 GMT 时间/日期转换为我当前的时区,即当前东部标准时间。因此,我想将“20090103 12:00”转换为“20090103 7:00”,任何有关如何执行此操作的信息将不胜感激。

有帮助吗?

解决方案

因为Perl内置的日期处理接口有点笨拙而且最终传递了六个变量,更好的方法是使用 DateTime Time :: Piece 。 DateTime是全唱,全舞蹈的Perl日期对象,你可能最终想要使用它,但Time :: Piece更简单,完全适合这项任务,具有5.10的优势,技术是两者基本相同。

以下是使用Time :: Piece和 strptime 的简单灵活方式

#!/usr/bin/perl

use 5.10.0;

use strict;
use warnings;

use Time::Piece;

# Read the date from the command line.
my $date = shift;

# Parse the date using strptime(), which uses strftime() formats.
my $time = Time::Piece->strptime($date, "%Y%m%d %H:%M");

# Here it is, parsed but still in GMT.
say $time->datetime;

# Create a localtime object for the same timestamp.
$time = localtime($time->epoch);

# And here it is localized.
say $time->datetime;

这是相反的方式。

由于格式是固定的,正则表达式会很好,但如果格式改变,你将不得不调整正则表达式。

my($year, $mon, $day, $hour, $min) = 
    $date =~ /^(\d{4}) (\d{2}) (\d{2})\ (\d{2}):(\d{2})$/x;

然后将其转换为Unix纪元时间(自1970年1月1日起的秒数)

use Time::Local;
# Note that all the internal Perl date handling functions take month
# from 0 and the year starting at 1900.  Blame C (or blame Larry for
# parroting C).
my $time = timegm(0, $min, $hour, $day, $mon - 1, $year - 1900);

然后回到当地时间。

(undef, $min, $hour, $day, $mon, $year) = localtime($time);

my $local_date = sprintf "%d%02d%02d %02d:%02d\n",
    $year + 1900, $mon + 1, $day, $hour, $min;

其他提示

以下是一个示例,使用 DateTime 及其 strptime 格式模块。

use DateTime;
use DateTime::Format::Strptime;

my $val = "20090103 12:00";

my $format = new DateTime::Format::Strptime(
                pattern => '%Y%m%d %H:%M',
                time_zone => 'GMT',
                );

my $date = $format->parse_datetime($val);

print $date->strftime("%Y%m%d %H:%M %Z")."\n";

$date->set_time_zone("America/New_York");  # or "local"

print $date->strftime("%Y%m%d %H:%M %Z")."\n";

$ perl dates.pl
20090103 12:00 UTC
20090103 07:00 EST


如果您想解析本地时间,请按照以下方式进行操作:

use DateTime;

my @time = (localtime);

my $date = DateTime->new(year => $time[5]+1900, month => $time[4]+1,
                day => $time[3], hour => $time[2], minute => $time[1],
                second => $time[0], time_zone => "America/New_York");

print $date->strftime("%F %r %Z")."\n";

$date->set_time_zone("Europe/Prague");

print $date->strftime("%F %r %Z")."\n";

这就是我要做的......

#!/usr/bin/perl
use Date::Parse;
use POSIX;

$orig = "20090103 12:00";

print strftime("%Y%m%d %R", localtime(str2time($orig, 'GMT')));

你也可以使用 Time :: ParseDate parsedate()代替 Date :: Parse str2time()。请注意事实上的标准atm。似乎是DateTime(但您可能不想仅使用OO语法来转换时间戳)。

任君选择:

毫无疑问,还有无数其他人,但他们可能是最有力的竞争者。

use strict;
use warnings;
my ($sec,$min,$hour,$day,$month,$year)=localtime();
$year+=1900;
$month+=1;
$today_time = sprintf("%02d-%02d-%04d %02d:%02d:%02d",$day,$month,$year,$hour,$min,$sec);
print $today_time;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top