如何將日期格式YYYY-MM-DDTHH:MM:SSZ轉換爲YYYY-MM-DD HH:MM + 8小時?Perl - 如何轉換日期?
例如:
Input: 2011-07-07T18:05:45Z
Output: 2011-07-08 02:05
如何將日期格式YYYY-MM-DDTHH:MM:SSZ轉換爲YYYY-MM-DD HH:MM + 8小時?Perl - 如何轉換日期?
例如:
Input: 2011-07-07T18:05:45Z
Output: 2011-07-08 02:05
讓我們從拉胡爾的片斷開始,並添加日期數學和輸出格式...
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";
我已經添加了使用日期時間::格式:: Strptime的,以指定所需的輸出格式。
然後我添加了三行代碼:
是否使用了DateTime模塊?
具體來說,下面是DateTime::Format::ISO8601的鏈接,它讀取/寫入您提到的ISO 8601格式作爲輸入。
取自
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 – abra
它不工作,結果是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;
如果沒有日期時間,你一定有時間::海賊王:
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";
+1很好的補充 – Rahul
-1,Time :: Piece有strftime和strptime – MkV
+1以抵消MkV的不合理downvote:Time :: Piece沒有提供任何計算,並且像下面的runrig那樣做像業餘愛好者一樣充滿錯誤(你好,DST轉換?)。 DateTime是適當的工具。 – daxim