2016-05-13 60 views
1

如何在perl中轉換1461241125.31307。我想:如何將perix中的unix時代轉換爲可讀格式

use Date::Parse; 
$unix_timestamp = '1461241125.31307'; 
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($unix_timestamp); 
$mon += 1; 
$year += 1900; 
$unix_timestamp_normal = "$year-$mon-$mday $hour:$min:$sec"; 

結果:2016-4-21 5:18:45(小時沒有填充)

我怎麼墊並使其GMT。我想要結果說2016-04-21 12:18:45


感謝您的答案人。

use DateTime; 
$unix_timestamp = '1461241125.31307'; 
my $dt = DateTime->from_epoch(epoch => $unix_timestamp); 
print $dt->strftime('%Y-%m-%d %H:%M:%S'),"\n"; 

回答

1
use POSIX qw(strftime); 

my $epoch_ts = '1461241125.31307'; 

say strftime('%Y-%m-%d %H:%M:%S', gmtime($epoch_ts)); 
4

最簡單的方法:

print scalar localtime $unix_timestamp; 

文檔:http://perldoc.perl.org/functions/localtime.html

對於GMT,使用gmtime

print scalar gmtime $unix_timestamp; 

文檔:http://perldoc.perl.org/functions/gmtime.html(基本上是說:一切都像localtime,但輸出GMT時間。)

對於自定義格式,嘗試DateTime

use DateTime; 

my $dt = DateTime->from_epoch(epoch => $unix_timestamp); 
print $dt->strftime('%Y-%s'); 

所有選項見http://search.cpan.org/perldoc?DateTime。格式批次可以更容易地使用預定義的日期時間格式化程序創建:http://search.cpan.org/search?query=DateTime%3A%3AFormat&mode=all

+0

使用POSIX的strftime比使用多更輕便DateTime的(而且是核心) – ikegami

0

使用gmtime,而不是localtime

perldoc -f gmtime

gmtime EXPR 
gmtime Works just like "localtime" but the returned values are localized 
     for the standard Greenwich time zone. 

     Note: When called in list context, $isdst, the last value returned 
     by gmtime, is always 0. There is no Daylight Saving Time in GMT. 

     Portability issues: "gmtime" in perlport. 
相關問題