Perl 日期时间减法问题
我在将两个日期时间对象相减时遇到了一个小问题。我使用以下代码:
$today = DateTime->now( time_zone => 'Europe/Berlin' );
my $dt1 = DateTime-> new (
year => 2011,
month => 08,
day => 08,
hour => 1,
minute => 0,
second => 4,
time_zone =>'Europe/Berlin'
);
print "DT1 : $dt1\n";
print "today: $today\n";
my $sub = $today->subtract_datetime($dt1);
print "sub days: ".$sub->days."\n";
DT1 和今天的打印语句打印:
DT1 : 2011-08-08T01:00:04
today: 2011-08-16T08:34:10
但是如果我在减法之后打印 $sub->days
值,它会显示 1 而不是 < 8天。
我的减法有错误吗?
非常感谢您的帮助。
I've got a little problem by subtracting two datetime objects from each other. I use the following code:
$today = DateTime->now( time_zone => 'Europe/Berlin' );
my $dt1 = DateTime-> new (
year => 2011,
month => 08,
day => 08,
hour => 1,
minute => 0,
second => 4,
time_zone =>'Europe/Berlin'
);
print "DT1 : $dt1\n";
print "today: $today\n";
my $sub = $today->subtract_datetime($dt1);
print "sub days: ".$sub->days."\n";
The print statement for DT1 and today prints:
DT1 : 2011-08-08T01:00:04
today: 2011-08-16T08:34:10
But if I print after the subtraction the $sub->days
value it shows 1 instead of 8 days.
Do I have a error in my subtraction?
Many thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DateTime::Duration
无法按您(和我)的预期工作。检查$sub
的所有字段:两个日期之间的差异为1周+1天,即预期的8天。
如果您想要天数差异,请尝试
$today->delta_days( $dt1 )
。 delta_days() 方法返回一个持续时间,其中仅包含天(编辑)和周,但不包含月。The
DateTime::Duration
does not work as you (and I) expected. Check all fields of$sub
:The difference between the two dates is 1 week + 1 day, the expected eight days.
If you want the difference in days, try
$today->delta_days( $dt1 )
. The delta_days() method returns a duration which contains only days (edit) and weeks, but not months.所得持续时间为 1 周零 1 天。周可以安全地转换为天,因此您可以使用“记住”获得所需的结果。
请记住,月不能转换为天,并且减法可以产生月份的持续时间。因此,您确实想使用
PS — 08 是一个错误:
删除前导零。
The resulting duration is of 1 week and 1 day. Weeks can be safely converted to days, so you can get the desired result using
Keep in mind that months cannot be converted into days, and subtraction can produce durations with months. As such, you really want to use
PS — 08 is an error:
Drop the leading zero.