将字符串从GMT转换为EST

时间:2015-01-27 01:40:06

标签: perl datetime

我试图将GMT中提供的日期戳的字符串值转换为EST(或GMT -5)中的正确时间。我没有理解如何使用GMT将值传递给函数并返回EST值。

Source Value看起来像这样:2015-01-01 17:05:53

我需要返回2015-01-01 12:05:53

任何帮助表示赞赏...

谢谢!

2 个答案:

答案 0 :(得分:1)

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

# Use DateTime::Format::Strptime to parse your date string
use DateTime::Format::Strptime;

my $format  = '%F %T'; # This is the format of your date/time strings
my $from_tz = 'UTC';
my $to_tz   = '-0500';

# Create a parser object that knows the strings it is given are in UTC
my $parser = DateTime::Format::Strptime->new(
    pattern   => $format,
    time_zone => $from_tz,
);

my $in_date = '2015-01-01 17:05:53';

# Use the parser to convert your string to a DateTime object
my $dt = $parser->parse_datetime($in_date);

# Use DateTime's set_time_zone() method to change the time zone
$dt->set_time_zone($to_tz);

# Print the (shifted) date/time string in the same format
say $dt->strftime($format);

答案 1 :(得分:-1)

使用DateTime :: Format :: Strptime获取DateTime对象,然后将时区设置为“UTC”,然后设置“-0500”以获得转换

use DateTime::Format::Strptime;

my $parser = DateTime::Format::Strptime->new(pattern => "%Y-%m-%d %H:%M:%S");
$datetime=$parse->parse_datetime("2015-01-01 17:05:53");

$datetime->set_time_zone("UTC");
$datetime->set_time_zone("-0500");

print $datetime->strftime("%Y-%m-%d %H:%M:%S");

有关更多信息,请参阅CPAN文档:

http://search.cpan.org/~drolsky/DateTime-Format-Strptime-1.56/lib/DateTime/Format/Strptime.pm

http://search.cpan.org/~drolsky/DateTime-1.18/lib/DateTime.pm