laziness, impatience, and hubris PerlMonks

### Re^5: Check if Date interval contains Hour X

by alexm (Chaplain)
 on Jul 23, 2009 at 21:33 UTC ( #782792=note: print w/replies, xml ) Need Help??

You're right again, I just realized a bit later so I've been playing with intersects:

```sub hour_in_range {
my (\$dt_s, \$dt_e, @hours) = @_;

my \$dt_span = DateTime::Span->from_datetimes(
start => \$dt_s, end => \$dt_e
);

for my \$hour (@hours) {
my \$dt = \$dt_s->clone()
->truncate( to => 'day' )

\$dt->add( days => 1 ) if \$dt < \$dt_s;

my \$hour_span = DateTime::Span->from_datetimes(
start => \$dt, end => \$dt
);

return 1 if \$dt_span->intersects(\$hour_span);
}

return 0;
}

It's not as simple and efficient as your approach, but it shows how to use span intersection.

OTOH, I misunderstood the OP and was thinking that @hours = (1,11) was an interval (1am to 11am), not a list of hours to match.

Replies are listed 'Best First'.
Re^6: Check if Date interval contains Hour X
by ikegami (Pope) on Jul 23, 2009 at 21:44 UTC
```        my \$hour_span = DateTime::Span->from_datetimes(
start => \$dt, end => \$dt
);

should be

```        my \$hour_span = DateTime::Span->from_datetimes(
start => \$dt, before => \$dt->clone()->add( hours => 1 ),
);

```        my \$hour_span = DateTime::Span->new(
start => \$dt, hours => 1,
);

Update: No, neither fix help. They were suppose to make the following match:

```2010-10-10 01:59:59|2010-10-10 01:59:59|blablalblabla

You need

```sub hour_in_range {
my (\$dt_s, \$dt_e, @hours) = @_;

my \$dt_span = DateTime::Span->from_datetimes(
start => \$dt_s, end => \$dt_e
);

for my \$hour (@hours) {
my \$dt = \$dt_s->clone()
->truncate( to => 'day' )

my \$dt_tomorrow = \$dt->clone()->add( days => 1 );

my \$hour_span = DateTime::Span->new(
start => \$dt, hours => 1
)->union( DateTime::Span->new(
start => \$dt_tomorrow, hours => 1
));

return 1 if \$dt_span->intersects(\$hour_span);
}

return 0;
}

And there you go, the four DateTimes per hour I mentioned earlier.

And there you go, the four DateTimes per hour I mentioned earlier.

Wow! I'm still a beginner with DateTime modules, and today I learnt a few things. Thanks a lot!

Create A New User
Node Status?
node history
Node Type: note [id://782792]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2017-11-18 20:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In order to be able to say "I know Perl", you must have:

Results (277 votes). Check out past polls.

Notices?