【发布时间】:2014-11-20 11:38:30
【问题描述】:
这两行是测试数据
my $dt = DateTime->new( {
year => 2014, month => 9, day => 19,
hour => 00, minute=> 00, second=> 00});
$dt->set_time_zone(DateTime::TimeZone->new( name => 'America/Sao_Paulo' ));
现在我想用失败的日期添加一个月
$dt->add ( months => 1 );
# This fails because the result date is 2014-10-19 00:00:00 and for Sao_Paulo
# the result should be a DST shifted time 2014-10-19 01:00:00
我想出的最简单的解决方案是这样的
my $tz_backup = $dt->time_zone(); # Backup the timezone
$dt->set_time_zone('UTC'); # Moving the time to UTC to get rid of DST complexities
$dt->add ( months => 1 ); # Perform the original operation
$dt->set_time_zone($tz_backup); # Setting back the original timezone
问题是,这个解决方案是否存在任何缺陷?
如果这种方法确实适用于所有时区和所有 DST 场景,那么为什么 perl DateTime 库自己不这样做呢? 如果我的解决方案是正确的,则不需要回答这个问题;)
谢谢
【问题讨论】:
-
当我运行您的原始代码时,我收到“时区日期的本地时间无效”错误。
-
你没有提到你想用这些变异的日期时间对象做什么,但在我看来你可能对时间字段不感兴趣。我建议,与其费力维护一个有效的日期时间,不如简单地将值转换为一个
Date::Simple对象,该对象没有可能“无效”的时间字段。 -
我还认为您应该避免显式使用
DateTime::TimeZone类,而是将区域作为参数添加到构造函数:my $dt = DateTime->new(year => 2014, month => 9, day => 19, time_zone => 'America/Sao_Paulo')
标签: perl datetime timezone dst