如何在perl中转换1461241125.31307。我试过了:
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";
答案 0 :(得分: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。使用预定义的DateTime Formatters可以更轻松地创建大量格式:http://search.cpan.org/search?query=DateTime%3A%3AFormat&mode=all
答案 1 :(得分:1)
use POSIX qw( strftime );
my $epoch_ts = '1461241125.31307';
say strftime('%Y-%m-%d %H:%M:%S', gmtime($epoch_ts));
答案 2 :(得分: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.