2015-11-05 140 views
1

我需要使用Perl將曆元日期和時間字符串轉換爲UTC日期和時間。如何使用Perl將紀元時間轉換爲UTC時間?

請分享您的想法。

#!/usr/bin/perl 
my $start_time='1448841600'; 
my $stop_time='1448863200'; 

上述兩個日期和時間是時代格式,應該轉換爲UTC日期和時間。

+0

我的第一個想法是「爲什麼這些數字在引用的字符串?」 :-) –

回答

5

您可以使用gmtime做轉換,並且strftime做格式化。

use POSIX 'strftime'; 

    strftime "%d-%m-%Y-%H:%M:%S", gmtime('1448841600'); 
+2

協調通用時間(縮寫爲UTC,也稱爲格林威治標準時間或GMT)由[gmtime](http://perldoc.perl.org/functions/gmtime.html)返回。因此,不應使用'localtime',而應使用'gmtime'。 –

4

我建議使用Time::Piece模塊來操縱日期。

#!/usr/bin/env perl 

use strict; 
use warnings; 

use Time::Piece; 

my $start_time=Time::Piece -> new(1448841600); 


print $start_time,"\n"; 
print $start_time -> epoch,"\n"; 
print $start_time -> strftime ("%Y-%m-%d %H:%M:%S"),"\n"; 

#nb - you can also use localtime/gmtime: 
my $end_time = gmtime(1448863200); 
print $end_time,"\n"; 
print $end_time->epoch,"\n"; 

你也可以做時區數學所列出的位置:How can I parse dates and convert time zones in Perl?

2

可以使用gmtime功能:

my $time = "1448841600"; 
my @months = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); 
my ($sec, $min, $hour, $day,$month,$year) = (gmtime($time))[0,1,2,3,4,5]; 
print "Time ".$time." converts to ".$months[$month]." ".$day.", ".($year+1900); 
print " ".$hour.":".$min.":".$sec."\n"; 

輸出:

Time 1448841600 converts to Nov 30, 2015 0:0:0 
0

如果你需要做的更多在那些日期時間操作,use DateTime

use DateTime; 
my $start_time ='1448841600'; 
my $stop_time ='1448863200'; 
my $start = DateTime->from_epoch(epoch=>$start_time)->set_time_zone('UTC'); 
my $stop = DateTime->from_epoch(epoch=>$stop_time)->set_time_zone('UTC'); 
say $start->strftime("%F %T %Z"); # 2015-11-30 00:00:00 UTC 
say $stop->strftime("%F %T %Z"); # 2015-11-30 06:00:00 UTC 
相關問題