mikeman has asked for the wisdom of the Perl Monks concerning the following question:
When using DateTime::Span->intersects to check for intersections, the spans produced by DateTime::Span->from_datetime_and_duration, and those produced by DateTime::Span->from_datetimes, give what appear to be inconsistent results:
use strict; use warnings; use DateTime; use DateTime::Span; use Test::More 'no_plan'; my $dt1 = DateTime->new( day => 1, month => 1, year => 2011, hour => 12, minute => 0, second => 0, ); my $dt2 = $dt1->clone->add( hours => 1 ); my $duration = DateTime::Duration->new( hours => 1 ); { my $span = DateTime::Span->from_datetimes( start => $dt1, end => $dt2, ); diag $span->start->datetime(); diag $span->end->datetime(); is( $span->intersects( $dt1 ), 1, 'Spanset intersects $dt1' ); is( $span->intersects( $dt2 ), 1, 'Span intersects $dt2' ); is( DateTime::Duration->compare( $span->duration, $duration ), 0, 'Duration is 1 hour' ); } { my $span = DateTime::Span->from_datetime_and_duration( start => $dt1, duration => $duration, ); diag $span->start->datetime(); diag $span->end->datetime(); is( $span->intersects( $dt1 ), 1, 'Span intersects $dt1' ); is( $span->intersects( $dt2 ), 1, 'Span intersects $dt2' ); is( DateTime::Duration->compare( $span->duration, $duration ), 0, 'Duration is 1 hour' ); }
Here are the test results:
# 2011-01-01T12:00:00 # 2011-01-01T13:00:00 ok 1 - Spanset intersects $dt1 ok 2 - Span intersects $dt2 ok 3 - Duration is 1 hour # 2011-01-01T12:00:00 # 2011-01-01T13:00:00 ok 4 - Span intersects $dt1 not ok 5 - Span intersects $dt2 # Failed test 'Span intersects $dt2' # at /home/mike/test.t line 51. # got: '0' # expected: '1' ok 6 - Duration is 1 hour 1..6 # Looks like you failed 1 test of 6.
Note: subtracting one nanosecond from $dt2 in the failing test causes it to succeed:
is( $span->intersects( $dt2->clone->subtract( nanoseconds => 1 ) ), 1, 'Span intersects $dt2' );
It therefore looks as though one nanosecond is going missing somewhere.
Is this intentional -- am I missing something to do with DateTime::Duration objects, or is this down to a bug in one of the DateTime modules?
I'm using DateTime version 0.70 and DateTime::Span version 0.30 (the latest versions at the time of writing).
Update: After quite a lot of digging, I discovered that the new end of set created by DateTime::Span->from_datetime_and_duration is open by default -- it is a semi-open set with a start and open end. The end is therefore before the time+duration (by one nanosecond). That explains why the intersection is false.
The fact that the end of the set is open is stated in the docs, but I had not understood its ramifications. I'm still not clear on why the end of the set defaults to being open, but at least I can work around the issue I had.
|
|---|