开发者

Perl's Date::Manip - how to convert a given date into another timezone

Consider the following code snippet that takes user input (a date) and format it using UnixDate from Date::Manip

#!/usr/bin/perl
use Date::Mani开发者_开发技巧p;

my $input = join(" ", @ARGV);
my $date = UnixDate($input, "%Y-%m-%d %T"); 
print $date;

This was done to allow users to enter friendly dates such as "yesterday" or "1 week ago".

I would like to use $date with a different timezone (it will be used to extract SQL data). How would this be done? I did not find any construct of UnixDate that would allow to put a timezone, and I do not know either how to reformat the user input (concatenating the name of the timezone to it doesn't help).

Example

The user is somewhere in Central Europe (timezone: CET) and enters "today at 1pm". Execution of the code above is as follows:

$ ./test.pl today at 1pm
2011-03-03 13:00:00

This is the expected result as no timezone change are in effect. What I would like is to use that $date with another timezone, e.g. Pacific Standard (timezone: PST). In this case the output should be:

$ ./test.pl today at 1pm
2011-03-03 04:00:00


Try the Date_ConvTZ() function:

 my $date = UnixDate( Date_ConvTZ( $input, 'CET', 'PST' ), "%Y-%m-%d %T");

From the manual from Date::Manip::DM6


I don't know how to make Date::Manip understand timezones but this would be pretty straight forward with DateTime:

my $input = join(" ", @ARGV);
my $date  = UnixDate($input, "%Y-%m-%d %T");
$date =~ /(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/;
my $dt = DateTime->new(
    year      => $1,
    month     => $2,
    day       => $3,
    hour      => $4,
    minute    => $5,
    second    => $6,
    time_zone => 'CET',
);
$dt->set_time_zone('America/Vancouver'); # My DateTime::TimeZone doesn't have PST

You might be able to replace your Date::Manip uses with one or more of the DateTime modules too, DateTime is the standard date manipulation library for Perl so using it for all your date-time needs makes sense; OTOH, use what works for you and there's probably no harm in using both Date::Manip and DateTime if that gets the job done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜