【发布时间】:2011-09-30 17:53:17
【问题描述】:
如何将日期格式 YYYY-MM-DDTHH:MM:SSZ 转换为 YYYY-MM-DD HH:MM + 8 小时?
例如:
Input: 2011-07-07T18:05:45Z
Output: 2011-07-08 02:05
【问题讨论】:
如何将日期格式 YYYY-MM-DDTHH:MM:SSZ 转换为 YYYY-MM-DD HH:MM + 8 小时?
例如:
Input: 2011-07-07T18:05:45Z
Output: 2011-07-08 02:05
【问题讨论】:
让我们从 Rahul 的 sn-p 开始,然后添加日期数学和输出格式...
use DateTime;
use DateTime::Format::ISO8601;
use DateTime::Format::Strptime;
my $string = '2011-07-07T18:05:45Z';
my $dt = DateTime::Format::ISO8601->parse_datetime( $string );
die "Impossible time" unless $dt;
my $formatter = new DateTime::Format::Strptime(pattern => '%Y-%m-%d %T');
$dt->add( hours => 8 )->set_formatter($formatter);
print "$dt\n";
我添加了 DateTime::Format::Strptime 的使用,以指定所需的输出格式。
然后我又添加了三行:
【讨论】:
您在使用DateTime 模块吗?
具体来说,这里有一个指向DateTime::Format::ISO8601 的链接,它可以读取/写入您提到的作为输入的 ISO 8601 格式。
【讨论】:
如果你没有 DateTime,你肯定有 Time::Piece:
use strict;
use warnings;
use Time::Piece;
use Time::Seconds qw(ONE_HOUR);
my $str = '2011-07-07T18:05:45Z';
my $t = Time::Piece->strptime($str, "%Y-%m-%dT%TZ");
$t += 8 * ONE_HOUR;
print $t->strftime("%Y-%m-%d %H:%M"),"\n";
【讨论】:
取自
How can I validate a "yyyy-MM-dd'T'HH:mm:ssZ" date/timestamp in UTC with Perl?
use DateTime;
use DateTime::Format::ISO8601;
my $string = '2010-02-28T15:21:33Z';
my $dt = DateTime::Format::ISO8601->parse_datetime( $string ); die "Impossible time" unless $dt;
【讨论】:
它不起作用,结果是 2010-02-28T15:21:33
那么,努力去做吧……
use Time::Local
use warnings;
use strict;
$time = '2010-02-28T15:21:33Z';
my ($year, month, day) = split (/-/, $time)
$year -= 1900; #Year is an offset of 1900
$month -= 1; #Months are 0 - 11
#Now split the time off of the day (DDTHH:MM:SS)
$day = substr($day, 0, 2);
time = substr($day, 3)
#Now split the time
(my $hour, $minute, $second) = split(/:/, $time);
$second =~ s/Z$//; #Remove Z
my $time_converted = timelocal($second, $minute, $hour, $day, $month, $year);
#Now you have the time, Add eight hours
my $hours_in_seconds = 8 * 60 * 60;
$time_converted += $hours_in_seconds;
# Almost done: Convert time back into the correct array:
($second, $minute, $hour, $day, $month, $year) = localtime($time_converted);
$year += 1900;
$month += 1;
# Now, reformat:
my $formatted_time = sprint (%04d-%02d-%02d %02d:%02d),
$year, $month, $day, $hour, $minute;
【讨论】: