Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Check if Date interval contains Hour X

by ikegami (Patriarch)
on Jul 23, 2009 at 18:58 UTC ( [id://782760]=note: print w/replies, xml ) Need Help??


in reply to Check if Date interval contains Hour X

use strict; use warnings; use DateTime qw( ); use DateTime::Format::Strptime qw( ); # Returns true if range ($dt_s, $dt_e) # spans any part of any of the @hours. sub hour_in_range { my ($dt_s, $dt_e, @hours) = @_; # Find the floor. ( $dt_s = $dt_s->clone() ) ->truncate( to => 'hour' ); for my $hour (@hours) { ( my $dt = $dt_s->clone() ) ->set_hour($hour); $dt->add( days => 1 ) if $dt < $dt_s; return 1 if $dt <= $dt_e; } return 0; } { my @hours = (1, 11); # Hours to check my $parser = new DateTime::Format::Strptime( pattern => '%Y-%m-%d %H:%M:%S', time_zone => 'local', ); <DATA>; # Skip first line while (<DATA>) { chomp; my ($ts_s, $ts_e, $text) = split /\|/; my $dt_s = $parser->parse_datetime( $ts_s ); my $dt_e = $parser->parse_datetime( $ts_e ); if (hour_in_range($dt_s, $dt_e, @hours)) { print "Match\n"; } else { print "Not Match\n"; } } } __DATA__ Start_Time |End Time |TEXT 2009-07-22 08:00:00|2009-07-22 08:00:00|blablalblabla 2009-07-22 01:00:00|2009-07-22 01:00:00|blablalblabla 2009-07-22 08:00:00|2009-07-22 21:00:00|blablalblabla 2009-07-22 23:00:00|2009-07-23 00:00:00|blablalblabla 2009-07-22 23:00:00|2009-07-23 02:00:00|blablalblabla

Replies are listed 'Best First'.
Re^2: Check if Date interval contains Hour X
by alexm (Chaplain) on Jul 23, 2009 at 21:40 UTC

    Another (maybe simpler) way of truncating:

    sub hour_in_range { my ($dt_s, $dt_e, @hours) = @_; for my $hour (@hours) { my $dt = $dt_s->clone() ->truncate( to => 'day' ) ->add( hours => $hour ); $dt->add( days => 1 ) if $dt < $dt_s; return 1 if $dt <= $dt_e; } return 0; }
      That introduced a bug. hour_in_range no longer performs as documented. Test case:
      2010-10-10 01:59:59|2010-10-10 01:59:59|blablalblabla

        I see. In order to check only the hour (skipping minutes and seconds), $dt_s must be truncated to the hour.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://782760]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (6)
As of 2024-04-26 09:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found