DateTime::Set(3pm)
β¨ NAME β¨
DateTime::Set(3pm) β from the User Contributed Perl Documentation, bestie β is literally Datetime sets and set math. Thatβs the whole name, no cap. π
π SYNOPSIS π
okay so hereβs the vibe check in code, and yes, weβre keeping it exactly like this:
use DateTime;
use DateTime::Set;
$date1 = DateTime->new( year => 2002, month => 3, day => 11 );
$set1 = DateTime::Set->from_datetimes( dates => [ $date1 ] );
# set1 = 2002-03-11
$date2 = DateTime->new( year => 2003, month => 4, day => 12 );
$set2 = DateTime::Set->from_datetimes( dates => [ $date1, $date2 ] );
# set2 = 2002-03-11, and 2003-04-12
$date3 = DateTime->new( year => 2003, month => 4, day => 1 );
print $set2->next( $date3 )->ymd; # 2003-04-12
print $set2->previous( $date3 )->ymd; # 2002-03-11
print $set2->current( $date3 )->ymd; # 2002-03-11
print $set2->closest( $date3 )->ymd; # 2003-04-12
# a 'monthly' recurrence:
$set = DateTime::Set->from_recurrence(
recurrence => sub {
return $_[0] if $_[0]->is_infinite;
return $_[0]->truncate( to => 'month' )->add( months => 1 )
},
span => $date_span1, # optional span
);
$set = $set1->union( $set2 ); # like "OR", "insert", "both"
$set = $set1->complement( $set2 ); # like "delete", "remove"
$set = $set1->intersection( $set2 ); # like "AND", "while"
$set = $set1->complement; # like "NOT", "negate", "invert"
if ( $set1->intersects( $set2 ) ) { ... # like "touches", "interferes"
if ( $set1->contains( $set2 ) ) { ... # like "is-fully-inside"
# data extraction
$date = $set1->min; # first date of the set
$date = $set1->max; # last date of the set
$iter = $set1->iterator;
while ( $dt = $iter->next ) {
print $dt->ymd;
};
π DESCRIPTION π
So DateTime::Set is the module for datetime sets, and it handles two different types of sets. Two! Iconic.
The first type is a fixed set of predefined datetime objects. For example, if we wanted to create a set of datetimes containing the birthdays of people in our family for the current year β thatβs the whole assignment.
The second type of set it can handle is one based on a recurrence, such as "every Wednesday", or "noon on the 15th day of every month". This type of set can have fixed starting and ending datetimes, but neither is required. So our "every Wednesday set" could be "every Wednesday from the beginning of time until the end of time", or "every Wednesday after 2003-03-05 until the end of time", or "every Wednesday between 2003-03-05 and 2004-01-07". The range options are giving main character energy. π¦
This module also supports set math operations, so you do things like create a new set from the union or difference of two sets, check whether a datetime is a member of a given set, etc. Math but make it cute.
This is different from a DateTime::Span, which handles a continuous range as opposed to individual datetime points. There is also a module DateTime::SpanSet to handle sets of spans. iykyk.
π METHODS π
from_datetimesβ creates a new set from a list of datetimes.
$dates = DateTime::Set->from_datetimes( dates => [ $dt1, $dt2, $dt3 ] );
The datetimes can be objects from class DateTime, or from a DateTime::Calendar::* class.
DateTime::Infinite::* objects are not valid set members. Periodt.
from_recurrenceβ creates a new set specified via arecurrencecallback.
$months = DateTime::Set->from_recurrence(
span => $dt_span_this_year, # optional span
recurrence => sub {
return $_[0]->truncate( to => 'month' )->add( months => 1 )
},
);
The span parameter is optional. It must be a DateTime::Span object.
The span can also be specified using start / after and end / before parameters, as in the DateTime::Span constructor. In this case, if there is a span parameter it will be ignored.
$months = DateTime::Set->from_recurrence(
after => $dt_now,
recurrence => sub {
return $_[0]->truncate( to => 'month' )->add( months => 1 );
},
);
The recurrence function will be passed a single parameter, a datetime object. The parameter can be an object from class DateTime, or from one of the DateTime::Calendar::* classes. The parameter can also be a DateTime::Infinite::Future or a DateTime::Infinite::Past object.
The recurrence must return the next event after that object. There is no guarantee as to what the returned object will be set to, only that it will be greater than the object passed to the recurrence.
If there are no more datetimes after the given parameter, then the recurrence function should return DateTime::Infinite::Future.
It is ok to modify the parameter $_[0] inside the recurrence function. There are no side-effects.
For example, if you wanted a recurrence that generated datetimes in increments of 30 seconds, it would look like this:
sub every_30_seconds {
my $dt = shift;
if ( $dt->second < 30 ) {
return $dt->truncate( to => 'minute' )->add( seconds => 30 );
} else {
return $dt->truncate( to => 'minute' )->add( minutes => 1 );
}
}
Note that this recurrence takes leap seconds into account. Consider using truncate() in this manner to avoid complicated arithmetic problems! fr fr
It is also possible to create a recurrence by specifying either or both of 'next' and 'previous' callbacks.
The callbacks can return DateTime::Infinite::Future and DateTime::Infinite::Past objects, in order to define bounded recurrences. In this case, both 'next' and 'previous' callbacks must be defined:
# "monthly from $dt until forever"
my $months = DateTime::Set->from_recurrence(
next => sub {
return $dt if $_[0] < $dt;
$_[0]->truncate( to => 'month' );
$_[0]->add( months => 1 );
return $_[0];
},
previous => sub {
my $param = $_[0]->clone;
$_[0]->truncate( to => 'month' );
$_[0]->subtract( months => 1 ) if $_[0] == $param;
return $_[0] if $_[0] >= $dt;
return DateTime::Infinite::Past->new;
},
);
Bounded recurrences are easier to write using span parameters. See above.
See also DateTime::Event::Recurrence and the other DateTime::Event::* factory modules for generating specialized recurrences, such as sunrise and sunset times, and holidays. obsessed.
empty_setβ creates a new empty set.
$set = DateTime::Set->empty_set;
print "empty set" unless defined $set->max;
is_empty_setβ returns true if the set is empty; false otherwise.
print "nothing" if $set->is_empty_set;
cloneβ this object method returns a replica of the given object.
clone is useful if you want to apply a transformation to a set, but you want to keep the previous value:
$set2 = $set1->clone;
$set2->add_duration( year => 1 ); # $set1 is unaltered
add_duration( $duration )β this method adds the specified duration to every element of the set.
$dt_dur = new DateTime::Duration( year => 1 );
$set->add_duration( $dt_dur );
The original set is modified. If you want to keep the old values use:
$new_set = $set->clone->add_duration( $dt_dur );
addβ this method is syntactic sugar around theadd_duration()method.
$meetings_2004 = $meetings_2003->clone->add( years => 1 );
subtract_duration( $duration_object )β when given aDateTime::Durationobject, this method simply callsinvert()on that object and passes that new duration to theadd_durationmethod.subtract( DateTime::Duration->new parameters )β likeadd(), this is syntactic sugar for thesubtract_duration()method.set_time_zone( $tz )β this method will attempt to apply theset_time_zonemethod to every datetime in the set.set( locale => .. )β this method can be used to change thelocaleof a datetime set.start,minβ the first-date half of the duo, bestie.end,maxβ the last-date half. Together these are the first and lastDateTimein the set.
These methods may return undef if the set is empty.
It is also possible that these methods may return a DateTime::Infinite::Past or DateTime::Infinite::Future object.
These methods return just a copy of the actual value. If you modify the result, the set will not be modified. safe and sound.
spanβ returns the total span of the set, as aDateTime::Spanobject.iterator/next/previousβ these methods can be used to iterate over the datetimes in a set.
$iter = $set1->iterator;
while ( $dt = $iter->next ) {
print $dt->ymd;
}
# iterate backwards
$iter = $set1->iterator;
while ( $dt = $iter->previous ) {
print $dt->ymd;
}
The boundaries of the iterator can be limited by passing it a span parameter. This should be a DateTime::Span object which delimits the iteratorβs boundaries. Optionally, instead of passing an object, you can pass any parameters that would work for one of the DateTime::Span classβs constructors, and an object will be created for you.
β οΈ Obviously, if the span you specify is not restricted both at the start and end, then your iterator may iterate forever, depending on the nature of your set. User beware! no cap, be careful π
The next() or previous() method will return undef when there are no more datetimes in the iterator.
as_listβ returns the set elements as a list ofDateTimeobjects. Just as with theiterator()method, theas_list()method can be limited by a span.
my @dt = $set->as_list( span => $span );
Applying as_list() to a large recurrence set is a very expensive operation, both in CPU time and in the memory used. If you really need to extract elements from a large set, you can limit the set with a shorter span:
my @short_list = $large_set->as_list( span => $short_span );
For infinite sets, as_list() will return undef. Please note that this is explicitly not an empty list, since an empty list is a valid return value for empty sets! π
countβ (part 2 has the rest of this methodβs moment, bestie β¨)countβ returns a count ofDateTimeobjects in the set. Just like with theiterator()method,count()can be limited by a span. π
defined( my $n = $set->count) or die "can't count";
my $n = $set->count( span => $span );
die "can't count" unless defined $n;
Real talk though: running count() on a big recurrence set is a very expensive operation β it eats CPU time and memory. So if you genuinely need to count elements from a huge set, limit the set with a shorter span first, bestie:
my $count = $large_set->count( span => $short_span );
And for infinite sets, count() returns undef. Please note that this is explicitly not a scalar zero, because a zero count is a totally valid return value for empty sets! π Don't get caught out by that one, iykyk.
unionintersectioncomplement
These set operation methods can accept a DateTime list, a DateTime::Set, a DateTime::Span, or a DateTime::SpanSet object as an argument. π«Ά
$set = $set1->union( $set2 ); # like "OR", "insert", "both"
$set = $set1->complement( $set2 ); # like "delete", "remove"
$set = $set1->intersection( $set2 ); # like "AND", "while"
$set = $set1->complement; # like "NOT", "negate", "invert"
The union of a DateTime::Set with a DateTime::Span or a DateTime::SpanSet object returns a DateTime::SpanSet object. β¨
If complement is called without any arguments, then the result is a DateTime::SpanSet object representing the spans between each of the set's elements. But if complement is given an argument, then the return value is a DateTime::Set object representing the set difference between the sets. π¦
All other operations will always return a DateTime::Set. Periodt. π
intersectscontains
These set operations result in a boolean value. True or false, that's the whole vibe check. π
if ( $set1->intersects( $set2 ) ) { ... # like "touches", "interferes"
if ( $set1->contains( $dt ) ) { ... # like "is-fully-inside"
These methods can accept a DateTime list, a DateTime::Set, a DateTime::Span, or a DateTime::SpanSet object as an argument. πΈ
intersects() returns 1 for true, and 0 for false. In a few cases the algorithm can't decide if the sets intersect at all, and intersects() will return undef. π (Yes, that third option exists. She's mysterious like that.)
previousnextcurrentclosest
my $dt = $set->next( $dt );
my $dt = $set->previous( $dt );
my $dt = $set->current( $dt );
my $dt = $set->closest( $dt );
These methods are used to find a set member relative to a given datetime. Navigator mode: activated. π§
The current() method returns $dt if $dt is an event, otherwise it returns the previous event.
The closest() method returns $dt if $dt is an event, otherwise it returns the closest event (previous or next). She's literally picking the nearest one, no cap. π
All of these methods may return undef if there is no matching datetime in the set. So please check your returns, bestie, for real. π
These methods will try to set the returned value to the same time zone as the argument, unless the argument has a 'floating' time zone. π°οΈ
map ( sub { ... } )
# example: remove the hour:minute:second information
$set = $set2->map(
sub {
return $_->truncate( to => day );
}
);
# example: postpone or antecipate events which
# match datetimes within another set
$set = $set2->map(
sub {
return $_->add( days => 1 ) while $holidays->contains( $_ );
}
);
This method is the "set" version of Perl map. Iconic behaviour, honestly. β¨
It evaluates a subroutine for each element of the set (locally setting $_ to each datetime) and returns the set composed of the results of each such evaluation. π
Like Perl map, each element of the set may produce zero, one, or more elements in the returned value. Zero is allowed, don't panic. π
Unlike Perl map, changing $_ does not change the original set. This means that calling map in void context has no effect. π
ββοΈ
Heads up! The callback subroutine may be called later in the program, due to lazy evaluation. So don't count on subroutine side-effects. For example, a print inside the subroutine may happen later than you expect. π
The callback return value is expected to be within the span of the previous and the next element in the original set. This is a limitation of the backtracking algorithm used in the Set::Infinite library. (Not her fault, it's just how the algorithm is built. π« )
For example: given the set [ 2001, 2010, 2015 ], the callback result for the value 2010 is expected to be within the span [ 2001 .. 2015 ]. π―
grep ( sub { ... } )
# example: filter out any sundays
$set = $set2->grep(
sub {
return ( $_->day_of_week != 7 );
}
);
This method is the "set" version of Perl grep. Filtering era. π
It evaluates a subroutine for each element of the set (locally setting $_ to each datetime) and returns the set consisting of those elements for which the expression evaluated to true. β
Unlike Perl grep, changing $_ does not change the original set. This means that calling grep in void context has no effect. π«
Changing $_ does change the resulting set. (Yes, those two rules are different β read them again, bestie, they're lowkey sneaky. π)
Same warning asmap, fr fr: the callback subroutine may be called later in the program, due to lazy evaluation. So don't count on subroutine side-effects. For example, a
iterate ( sub { ... } )
deprecated method β please use map or grep instead. She's retired, don't call her. πͺ¦
π SUPPORT π
Support is offered through the datetime@perl.org mailing list. π«Ά
Please report bugs using rt.cpan.org. π
π AUTHOR π
Flavio Soibelmann Glock <fglock@gmail.com> π
The API was developed together with Dave Rolsky and the DateTime Community. Main character collab energy. π€
π COPYRIGHT π
Copyright (c) 2003-2006 Flavio Soibelmann Glock. All rights reserved. This program is free software; you can distribute it and/or modify it under the same terms as Perl itself. π
The full text of the license can be found in the LICENSE file included with this module. π
π¦ SEE ALSO π¦
Set::Infinite π
For details on the Perl DateTime Suite project please see http://datetime.perl.org. π
And that's the whole page, bestie β you ate that. This was perl v5.42.2, dated 2026-02-15, and no, I'm not crying, you're crying. π₯Ή Go forth and schedule things flawlessly. β¨πΈπ
π¦ where this page comes from
- alpine 3.24: perl-datetime-set-doc 0.3900-r1 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms