2

I need to convert epoch date and time string to UTC date and time using Perl.

Kindly share your thoughts.

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

The above two date and times are in epoch format and those should be converted to UTC date and time.

zdim
  • 64,580
  • 5
  • 52
  • 81
Madhan
  • 1,291
  • 3
  • 21
  • 34

6 Answers6

6

You can use gmtime to do the conversion, and strftime to do the formatting.

  use POSIX 'strftime';

  strftime "%d-%m-%Y-%H:%M:%S", gmtime('1448841600');
ikegami
  • 367,544
  • 15
  • 269
  • 518
loganaayahee
  • 809
  • 2
  • 8
  • 13
  • 2
    Coordinated Universal Time (abbreviated as UTC, also called Greenwich Mean Time or GMT) is returned by [gmtime](http://perldoc.perl.org/functions/gmtime.html). So instead of `localtime` you should use `gmtime`. – Arunesh Singh Nov 05 '15 at 10:32
4

I would suggest using the Time::Piece module for manipulating dates.

#!/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";

You can also do timezone maths as outlined here: How can I parse dates and convert time zones in Perl?

Community
  • 1
  • 1
Sobrique
  • 52,974
  • 7
  • 60
  • 101
3

Use gmtime to get the UTC time.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
thepace
  • 2,221
  • 1
  • 13
  • 21
3

If you need to do more manipulations on those datetime, 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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
2

You can use gmtime function:

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";

Output:

Time 1448841600 converts to Nov 30, 2015 0:0:0
serenesat
  • 4,611
  • 10
  • 37
  • 53
1

perl -E 'say scalar gmtime(1638884356)'

same for localtime

mestia
  • 450
  • 2
  • 7