如何使用 Perl 将纪元时间转换为 UTC 时间?

Posted

技术标签:

【中文标题】如何使用 Perl 将纪元时间转换为 UTC 时间?【英文标题】:How to convert epoch time to UTC time using Perl? 【发布时间】:2016-02-06 02:35:14 【问题描述】:

我需要使用 Perl 将纪元日期和时间字符串转换为 UTC 日期和时间。

请分享你的想法。

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

以上两个日期时间为纪元格式,需转换为UTC日期时间。

【问题讨论】:

我的第一个想法是“为什么这些数字在引号中?” :-) 【参考方案1】:

您可以使用gmtime 进行转换,使用strftime 进行格式化。

  use POSIX 'strftime';

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

【讨论】:

协调世界时(缩写为 UTC,也称为格林威治标准时间或 GMT)由 gmtime 返回。所以你应该使用gmtime,而不是localtime【参考方案2】:

我建议使用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?

【讨论】:

【参考方案3】:

如果您需要对这些日期时间进行更多操作,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

【讨论】:

【参考方案4】:

使用gmtime 获取UTC 时间。

【讨论】:

【参考方案5】:

你可以使用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

【讨论】:

【参考方案6】:

perl -E 'say scalar gmtime(1638884356)'

本地时间相同

【讨论】:

以上是关于如何使用 Perl 将纪元时间转换为 UTC 时间?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Perl 中将纪元时间转换为正常时间?

使用 c++ 将纪元毫秒转换为 UTC 日期和时间

将日期、时间和 UTC 偏移值转换为自 unix 纪元以来的毫秒数?

如何在 Perl 中将 dd/mm/yyyy 转换为纪元时间?

Unix 纪元时间戳在 Python 中转换为 UTC 时区

将UTC时间戳转换为C中的纪元时间[重复]