GMT to MST timestamp conversion

Hi Team,

We have written a perl script to perform the GMT to MST timestamp conversion.

Input: 2013-12-01T05:23:19.374
Output: need the given timestamp in MT (MST/MDT)

#!/usr/bin/perl
use strict;
use warnings;
use Time::Local;

#always gmt
#my $tval = '2013-12-01T05:23:19.374';

my ($year,$month,$day,$hour,$min,$sec,$mil) = $ARGV[0] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2}).(\d{3})$/;
print "$year-$month-$day $hour:$min:$sec\n";
my $seconds = timelocal($sec, $min, $hour, $day, $month-1, $year);
($sec, $min, $hour,$day,$month, $year) = localtime($seconds-25200);

printf "%04d-%02d-%02d %02d:%02d:%02d", $year+1900, $month+1, $day, $hour, $min, $sec;

GMT is 7 hrs ahead of MST and 8 hrs ahead of MDT. Since we have hard coded 25200 the given timestamp is always converted to MST. Can someone help us to make it dynamic.. like.. during day light savings, the 8 hrs has to be deducted else 7 hrs.

Thanks
Krishnakanth

Does it need to be perl? From shell script you could do:

$ TZ=MST date -d "2013-12-01 05:23:19.374 GMT"
Sat Nov 30 22:23:19 MST 2013
1 Like

Kmanivan,

The call to timelocal should be to timegmt as the argument is in GMT. You then can eliminate adjusting the value of seconds by 25200 when you call localtime .

For example:

#!/usr/bin/perl
use strict;
use warnings;
use Time::Local;
use POSIX qw{ strftime }

my @T = $ARGV[0] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})(?:\.\d+)$/;
print strftime("%Y-%m-%d %H:%M:%S %Z%n", localtime timegmt reverse @T);

Hi derekludwig,

Thank you for your reply.

I am getting syntax err.

syntax error at GMT2MST.pl line 7, near "my "

Can you help me to fix the issue?

Thanks

How about this change to your original code:

#!/usr/bin/perl
use strict;
use warnings;
use Time::Local;
use POSIX qw(tzset);

#always gmt
#my $tval = '2013-12-01T05:23:19.374';

my ($year,$month,$day,$hour,$min,$sec,$mil) = $ARGV[0] =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2}).(\d{3})$/;
print "$year-$month-$day $hour:$min:$sec\n";
$ENV{TZ}="GMT";
tzset;
my $seconds = timelocal($sec, $min, $hour, $day, $month-1, $year);
$ENV{TZ}="MST";
tzset;
($sec, $min, $hour,$day,$month, $year) = localtime($seconds);

printf "%04d-%02d-%02d %02d:%02d:%02d\n", $year+1900, $month+1, $day, $hour, $min, $sec;