# Some examples for the FAQ

use DateTime::Event::Recurrence;

{

# 6.2: How do I check whether two dates and times lie
more or less than a given time interval apart?

my $dt1  = DateTime->new(year => 2002, month => 3,
day => 1);
my $dt2  = DateTime->new(year => 2002, month => 2,
day => 11);
$interval = DateTime::Duration->new( days => 19,
hours => 3, minutes => 12);

$span = DateTime::Span->from_datetimes( 
      start => $dt1 - $interval,
      end =>   $dt1 + $interval );

$span->contains( $dt2 ) ? print 'closer than
interval' : print 'too far apart';
print "\n";

}

{

# 6.6: How do I calculate the date of the Wednesday
of the same week as the current date?

my $weeks = DateTime::Event::Recurrence->weekly;

print "current wed is ", $weeks->current(
DateTime->now )->add( days => 2 )->ymd, "\n" ;

}

{

# 6.7: How do I calculate the last and the next
Saturday for any given date?

my $sats = DateTime::Event::Recurrence->weekly( days
=> [ 6 ] );

print "last sat was ", $sats->previous(
DateTime->today )->ymd , " and next sat will be " ,
$sats->next( DateTime->today )->ymd , "\n" ;

}

{

# 6.8: How can I calculate the last business day
(payday!) of a month?

my $week_days = DateTime::Event::Recurrence->weekly(
days => [ 1..5 ] );

print "Last biz day is ", $week_days->previous(
DateTime->now->truncate( to => 'month' )->add( months
=> 1 ) )->ymd , "\n" ;

}

{

# 6.9: How can I find what day the third Friday of a
month is on?

use DateTime::Event::ICal;

my $third_friday = DateTime::Event::ICal->recur( freq
=> 'monthly', byday => [ '+3fr' ] );

print "3rd friday this month is ",
$third_friday->next( DateTime->now->truncate( to =>
'month' ) )->ymd , "\n" ;

}

{

# 6.12: How can I calculate the difference in days
between dates, 
# but without counting Saturdays and Sundays?

my $end_dt =   DateTime->today +
DateTime::Duration->new( days => 14 );

my $week_days = DateTime::Event::Recurrence->weekly(
days => [ 1..5 ] );

$days = $week_days->count( start => DateTime->today,
end => $end_dt );

print "There are $days week days between today and "
, $end_dt->ymd , "\n" ;

}

{

# 7.1: How do I do business week calculations?
# e.g. 3 business days from now... 

# Note: this is a cheat - 'select' is a Set::Infinite
method that makes a 'slice'.
# There may be a way to do this using DT::E::ICal.

my $week_days = DateTime::Event::Recurrence->weekly(
days => [ 1..5 ] );

$days_from_now = $week_days->intersection( 
                     DateTime::Span->from_datetimes(
start => DateTime->today ) );

my $n = 3;
print "$n biz days from now will be ",
$days_from_now->{set}->select( by => [ $n - 1 ]
)->min->ymd , "\n" ;

}

# - Flavio S. Glock

Reply via email to