How do I convert epoch time to normal time in Perl?

不打扰是莪最后的温柔 提交于 2019-12-05 07:58:13

You can use ctime, depending on your definition of "Normal time":

Example code:

use Time::Local; 
use Time::localtime; 
my $time=timelocal(1,2,3,24,6,2010);
print "$time\n"; 
$theTime = ctime($time); 
print "$theTime\n";

Result:

1279954921
Sat Jul 24 03:02:01 2010

Also, you don't need to use Time::Localtime (which is why you get Time::tm instead of a standard array/string from Perl's internal localtime):

use Time::Local; 
my $time=timelocal(1,2,3,24,6,2010); 
print "$time\n"; 
$theTime = localtime($time); 
print "$theTime\n";

1279954921
Sat Jul 24 03:02:01 2010
Greg Bacon

Don't forget to subtract 1900 from the year!

Remember that in scalar context, localtime and gmtime returns a ctime-formatted string, so you could use it as in the following. If that's unsuitable, you might want to use strftime from the POSIX module.

#! /usr/bin/perl

use warnings;
use strict;

use Time::Local;

my $start = "01:02:03";
my $end   = "01:02:05";
my $date  = "2010-02-10";

my($year,$mon,$mday) = split /-/, $date;
$mon--;
$year -= 1900;

my($startTime,$endTime) =
  map { my($hour,$min,$sec) = split /:/;
        timelocal $sec,$min,$hour,$mday,$mon,$year }
  $start, $end;

for (my $i = $startTime; $i <= $endTime + 29; $i++) {
  print scalar localtime($i), "\n";
}

print "$startTime   $endTime \n";

Tail of the output:

Wed Feb 10 01:02:26 2010
Wed Feb 10 01:02:27 2010
Wed Feb 10 01:02:28 2010
Wed Feb 10 01:02:29 2010
Wed Feb 10 01:02:30 2010
Wed Feb 10 01:02:31 2010
Wed Feb 10 01:02:32 2010
Wed Feb 10 01:02:33 2010
Wed Feb 10 01:02:34 2010
1265785323   1265785325
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!