Date::Calc::Object(3)
๐ Date::Calc::Object(3) ๐
okay so this is the User Contributed Perl Documentation page for Date::Calc::Object, and it's literally the object-oriented add-on for Date::Calc with overloaded operators. periodt. โจ
๐ธ NAME ๐ธ
Date::Calc::Object - Object-oriented add-on for Date::Calc with overloaded operators. ๐ซถ
๐ MOTTO ๐
Make frequent things easy and infrequent or hard things possible
๐ PREFACE ๐
okay bestie, listen: you do NOT need to add use Date::Calc qw(...); on top of this module. Nope. ๐
โโ๏ธ
You just do:
use Date::Calc::Object qw(...);
INSTEAD OF
use Date::Calc qw(...);
with the same qw(...) you'd use with the Date::Calc module, and then forget about Date::Calc::Object altogether. The rest of your existing code doesn't change at all. fr fr. ๐ฏ
Also: to create a new date object, you do not need to use
$date_object = Date::Calc::Object->new(...);
(but you may), and should use
$date_object = Date::Calc->new(...);
instead (saves you some typing and is a trifle faster). slay. โญ
โจ SYNOPSIS โจ
๐๏ธ Export tags
:all - all functions from Date::Calc
:aux - auxiliary functions shift_*
:ALL - both :all and :aux
๐งฐ Functions
See Date::Calc(3) for a list of available functions. ๐
$year = shift_year(\@_);
($year,$mm,$dd) = shift_date(\@_);
($hrs,$min,$sec) = shift_time(\@_);
($year,$mm,$dd,$hrs,$min,$sec) = shift_datetime(\@_);
๐ ๏ธ Methods
$old = Date::Calc->accurate_mode([FLAG]);
$old = Date::Calc->normalized_mode([FLAG]);
$old = Date::Calc->number_format([NUMBER|CODEREF]);
$old = Date::Calc->delta_format([NUMBER|CODEREF]); # global default
$old = Date::Calc->date_format([NUMBER|CODEREF]); # global default
$old = Date::Calc->language([LANGUAGE]); # global default - DEPRECATED
$old = $date->accurate_mode([FLAG]); # is global nevertheless!
$old = $date->normalized_mode([FLAG]); # is global nevertheless!
$old = $date->number_format([NUMBER|CODEREF]); # is global nevertheless!
$old = $date->delta_format([NUMBER|CODEREF]); # individual override
$old = $date->date_format([NUMBER|CODEREF]); # individual override
$old = $date->language([LANGUAGE]); # individual override
$flag = $date->is_delta();
$flag = $date->is_date();
$flag = $date->is_short(); # i.e., has no time part
$flag = $date->is_long(); # i.e., has time part
$flag = $date->is_valid();
$date = Date::Calc->new([TYPE]);
$date = Date::Calc->new([TYPE,]YEAR,MONTH,DAY[,HRS,MIN,SEC]);
$date = Date::Calc->new($arrayref);
$newdate = $somedate->new([TYPE]);
$newdate = $somedate->new([TYPE,]YEAR,MONTH,DAY[,HRS,MIN,SEC]);
$newdate = $somedate->new($arrayref);
$datecopy = $date->clone();
$targetdate->copy($sourcedate);
$targetdate->copy($arrayref);
$targetdate->copy(@list);
($year,$month,$day) = $date->date([TYPE]);
($year,$month,$day) = $date->date([TYPE,]YEAR,MONTH,DAY[,HRS,MIN,SEC]);
($year,$month,$day) = $date->date($arrayref);
([$hrs,$min,$sec]) = $date->time([TYPE]);
($hrs,$min,$sec) = $date->time([TYPE,]HRS,MIN,SEC);
([$hrs,$min,$sec]) = $date->time($arrayref);
($year,$month,$day,$hrs,$min,$sec) =
$date->datetime([TYPE]);
($year,$month,$day,$hrs,$min,$sec) =
$date->datetime([TYPE,]YEAR,MONTH,DAY[,HRS,MIN,SEC]);
$date = Date::Calc->today([FLAG]);
$date = Date::Calc->now([FLAG]); # shorthand for --+
$date = Date::Calc->today_and_now([FLAG]); # <-----+
$date = Date::Calc->gmtime([time]); # UTC/GMT
$date = Date::Calc->localtime([time]); # local time
$delta = Date::Calc->tzoffset([time]);
$date = Date::Calc->time2date([time]); # UTC/GMT
$date->today([FLAG]); # updates the date part only
$date->now([FLAG]); # updates the time part only
$date->today_and_now([FLAG]); # updates both date and time
$date->gmtime([time]); # updates both date and time (UTC/GMT)
$date->localtime([time]); # updates both date and time (local time)
$delta->tzoffset([time]); # updates both date and time
$date->time2date([time]); # updates both date and time (UTC/GMT)
$time = Date::Calc->mktime(); # same as "$time = CORE::time();"
$time = Date::Calc->date2time(); # same as "$time = CORE::time();"
$time = $date->mktime(); # converts into Unix time (local time)
$time = $date->date2time(); # converts into Unix time (UTC/GMT)
$year = $date->year([YEAR]);
$month = $date->month([MONTH]);
$day = $date->day([DAY]);
$hours = $date->hours([HRS]);
$minutes = $date->minutes([MIN]);
$seconds = $date->seconds([SEC]);
$number = $date->number([NUMBER|CODEREF]);
$string = $date->string([NUMBER|CODEREF][,LANGUAGE]);
$delta->normalize(); # renormalizes a delta vector
๐ช๏ธ Overloaded Operators
#####################################################
# Scalar operands are always converted into a delta #
# vector with that many days, i.e., [1,0,0,SCALAR] #
#####################################################
โ๏ธ Comparison Operators:
if ($date1 < $date2) { # compares date part only
if ($date1 <= $date2) { # compares date part only
if ($date1 > $date2) { # compares date part only
if ($date1 >= $date2) { # compares date part only
if ($date1 == $date2) { # compares date part only
if ($date1 != $date2) { # compares date part only
$comp = $date1 <=> $date2; # compares date part only
if ($date1 lt $date2) { # compares both date and time
if ($date1 le $date2) { # compares both date and time
if ($date1 gt $date2) { # compares both date and time
if ($date1 ge $date2) { # compares both date and time
if ($date1 eq $date2) { # compares both date and time
if ($date1 ne $date2) { # compares both date and time
$comp = $date1 cmp $date2; # compares both date and time
Note that you can of course also compare two deltas, but not a date and a delta!
##################################################
# Default TYPE for array refs in comparisons is: #
# Same as other operand #
##################################################
if ([2000,4,1] == $date) {
if ($today > [2000,4,1]) {
if ($now ge [2000,3,26,2,0,0]) {
if ($delta == [18,0,0]) {
if ($delta == -1) {
โ Plus:
$date2 = $date1 + $delta;
$date2 = $delta + $date1;
$date += $delta;
$this = $date++;
$next = ++$date;
$delta3 = $delta1 + $delta2;
$delta1 += $delta2;
$delta += $date; # beware of implicit type change!
$delta++;
++$delta;
#####################################################
# Default TYPE for array refs in '+' operations is: #
# Opposite of other operand #
#####################################################
$date2 = [2000,3,26] + $delta;
$date2 = $date1 + [+1,0,0];
$date2 = [0,0,-1] + $date1;
$date2 = $date1 + 1;
$date += [0,0,+1];
$date += 2;
$delta3 = [1,+1,0,-1] + $delta2;
$delta3 = $delta1 + [1,0,0,+1];
$delta3 = $delta1 + 1;
$delta += [1,0,+1,0];
$delta += [2000,3,26]; # beware of implicit type change!
$delta += 7;
โ Unary Minus:
$delta2 = -$delta1;
โ Minus:
$delta = $date2 - $date1;
$date2 = $date1 - $delta;
$date -= $delta;
$date2 -= $date1; # beware of implicit type change!
$this = $date--;
$prev = --$date;
$delta3 = $delta2 - $delta1;
$delta2 -= $delta1;
$delta--;
--$delta;
#####################################################
# Default TYPE for array refs in '-' operations is: #
# Always a date #
#####################################################
$delta = $today - [2000,3,26];
$delta = [2000,4,1] - $date;
$date2 = [2000,3,26] - $delta;
$date2 = $date1 - [1,0,0,+7];
$date2 = $date1 - 7;
$date -= [1,0,0,+1]; # better add [0,0,-1] instead!
$date2 -= [2000,3,26]; # beware of implicit type change!
$date2 -= 1;
$delta3 = [1,0,+1,0] - $delta1;
$delta3 = $delta2 - [1,0,0,-1];
$delta -= [1,0,0,+1];
$delta -= 7;
๐ฒ Miscellaneous Operators:
$string = "$date";
$string = "$delta";
print "$date\n";
print "$delta\n";
if ($date) { # date is valid
if ($delta) { # delta is valid
$days = abs($date);
$diff = abs($delta); # can be negative!
$diff = abs(abs($delta)); # always positive
๐ซ DESCRIPTION ๐ซ
FLAGโ okay soFLAGis either0(for "false") or1(for "true"). ๐
For accurate_mode() and normalized_mode(), this switches the corresponding mode on and off (see further below for an explanation of what these are).
For today(), now() and today_and_now(), a "true" value indicates "GMT" (Greenwich Mean Time), as opposed to local time, which is the default.
NUMBERโNUMBERis a number between0and2(fornumber_format()andnumber()) or between0and4(fordelta_format(),date_format()andstring()), indicating which of the three/five predefined formats, respectively, should be used for converting a date into numeric representation (needed for comparing dates, for instance) or string representation. ๐
Format #0 is the default at startup and the simplest of all (and should be fastest to calculate, too). โจ
The string representation of dates in format #0 also has the advantage of being sortable in chronological order (and of complying with ISO 8601).
(The numeric formats are (trivially) always sortable in chronological order of course.)
The other formats are (mostly) increasingly more sophisticated (in terms of esthetics and computation time) with increasing number (except for format #4):
Delta number formats (short):
0 13603
1 13603
2 13603
Delta string formats (short):
0 '+0+0+13603'
1 '+0 +0 +13603'
2 '+0Y +0M +13603D'
3 '+0 Y +0 M +13603 D'
4 '(0,0,13603)'
Date number formats (short):
0 20010401
1 730576
2 730576
Date string formats (short):
0 '20010401'
1 '01-Apr-2001'
2 'Sun 1-Apr-2001'
3 'Sunday, April 1st 2001'
4 '[2001,4,1]'
Delta number formats (long):
0 13603.012959
1 13603.012959
2 13603.0624884259
Delta string formats (long):
...and the list just keeps on giving ๐ :
0 '+0+0+13603+1+29+59'
1 '+0 +0 +13603 +1 +29 +59'
2 '+0Y +0M +13603D +1h +29m +59s'
3 '+0 Y +0 M +13603 D +1 h +29 m +29 s'
4 '(0,0,13603,1,29,59)'
Date number formats (long):
0 20010401.082959
1 730576.082959
2 730576.354155093
Date string formats (long):
0 '20010401082959'
1 '01-Apr-2001 08:29:59'
2 'Sun 1-Apr-2001 08:29:59'
3 'Sunday, April 1st 2001 08:29:59'
4 '[2001,4,1,8,29,59]'
Okay so if you pass a number that's outside the permitted range, or if the value isn't a code reference (peek the next section for the deets on that), then it just falls back to the default format #0 instead. No drama, it just defaults on you ๐ซถ.
โจ CODEREF โจ
CODEREF is the reference of a subroutine, and you can hand it over to the methods number_format(), delta_format() and date_format() to install a callback function. That callback gets called every single time a date (or delta) object needs to be converted into a number or a string โ even when it's happening implicitly ๐.
Like, this happens when you compare two date objects, or when you drop a date object reference into a string between double quotes. Sneaky implicit conversion, love that for us.
You can also pass that same CODEREF to the methods number() and string() when you want to explicitly convert a date object exactly how you want it. Boss move ๐
.
๐ธ LANGUAGE ๐ธ
LANGUAGE is either a number in the range [1..Languages()], or one of the strings Language_to_Text(1..Languages()) (go check Date::Calc(3) for that one, bestie).
๐ฆ TYPE ๐ฆ
TYPE is 0 for a regular date, and 1 for a delta vector (which is a list of year, month, day and optionally hours, minutes and seconds offsets). Simple as that โจ.
๐ Storage ๐
Date::Calc objects are implemented as two nested arrays. Yes, nested. It's giving inception, but honestly it slaps.
The "blessed" array โ whose reference is the object reference you get back when you call the new() method โ contains an anonymous array at position zero, and the object's data lives in its remaining fields.
That embedded anonymous array is where the object's attributes (flags) are stored.
Dates and delta vectors always comprise either 3 or 6 data values: year, month, day plus (optionally) hours, minutes and seconds.
Those values are stored in the blessed array at positions 1..3 or 1..6, respectively.
So an object without the time values is called "short", and an object that has time values is called "long" throughout this whole manual. That's the vocab, learn it, it's on the test ๐.
Hint: whenever you can, if you do NOT need the time values, just omit them โ like, always use the "short" form of the object if possible. It speeds up your calculations a little (the short form uses different, faster functions for all calculations internally). Free performance, bestie, take it.
The embedded anonymous array holds a bunch of flags:
At position zero, it contains the TYPE indicator, which decides whether the object is a date or a delta vector.
At position 1, the object stores the NUMBER of one of the delta vector formats โ or the reference of a callback function that converts the contents of the object into string representation if it's a delta vector โ or undef if the global settings apply.
At position 2, the object stores the NUMBER of one of the date formats โ or the reference of a callback function that converts the contents of the object into string representation if it's a date โ or undef if the global settings apply.
At position 3, the object stores the LANGUAGE to be used for all conversions into strings (where applicable), or undef if the global language setting applies.
Heads up: your callback functions (more on those in the section "Callback Functions" further below) should NOT pay attention to that value at position 3, because they get a parameter which tells them which language to use. That's necessary so temporary overrides can actually work, iykyk.
If your callback handlers use the *_to_Text* functions (or any other language-dependent function) from the Date::Calc module, your handlers should pass on this language parameter to those functions โ and not the value from position 3. Important โญ.
Be reminded though (and I cannot stress this enough): you should NEVER access the object's internal data directly, like through their positional numbers. ALWAYS go through their respective accessor methods, bestie:
year()
month()
day()
hours()
minutes()
seconds()
date()
time()
datetime()
is_delta()
is_date()
is_short()
is_long()
delta_format()
date_format()
language()
And even though position 4 and onward in the embedded anonymous array is currently unused, it might not stay that way in future releases of this module. So no stashing your stuff there, okay? ๐
So if you need more attributes in a subclass of the Date::Calc[::Object] class, the suggestion is to use values starting at positions a bit further up โ like 6, 8 or 10. Future-proof your vibes ๐.
๐ Invalid Dates ๐
Only new() lets you create objects containing possibly invalid dates. That's needed for reading in and evaluating user input, for example. Everyone else has to behave ๐ญ.
๐ Usage ๐
These methods:
accurate_mode()
normalized_mode()
number_format()
delta_format()
date_format()
language()
date()
time()
datetime()
year()
month()
day()
hours()
minutes()
seconds()
are used for reading and for setting attributes. Call them with no parameters and they simply return the values in question. Read mode, unlocked ๐ฅ.
And these methods:
accurate_mode()
normalized_mode()
number_format()
delta_format()
date_format()
language()
always return the previous value when a new value is set. That's so you can change these values temporarily and restore the old value afterwards way more easily (though you can also just override the "format" and "language" settings directly when you call the number() or string() method โ options, we love options).
Meanwhile these methods:
date()
time()
datetime()
year()
month()
day()
hours()
minutes()
seconds()
always return the new values once the corresponding values have been changed. Fresh off the press โจ.
The method date() NEVER returns the time values (hours, minutes, seconds) โ even if they were literally just set using this method (which the method optionally allows, cheeky). Why? Because otherwise it'd be super hard to predict the exact number of values it returns, and that could lead to errors (wrong number of parameters) elsewhere in your program. It's for your own good ๐ซถ.
The method datetime() ALWAYS returns the time values (hours, minutes, seconds), even if the object in question has no time part at all. In that case, zeros get returned for hours, minutes and seconds instead โ but the stored time part is left completely unchanged, whether it exists or not. No sneaky edits ๐
.
If you don't provide values for hours, minutes and seconds when you use the method date() to set year, month and day, the time part will not be changed (whether it exists or not).
If you don't provide values for hours, minutes and seconds when you use the method datetime() to set year, month and day, the time part gets filled with zeros โ and the time part gets created if necessary.
If the object is short, like, if it has no time values, the method time() returns an empty list.
If the object is short and the methods hours(), minutes() or seconds() are used to set any of these time values, the object is automatically promoted to the "long" form, and the other two time values get filled with zeros. Glow-up, automatic ๐.
The following methods can also return undef under certain circumstances:
delta_format()
date_format()
language()
is_delta()
is_date()
is_short()
is_long()
is_valid()
hours()
minutes()
seconds()
number()
string()
Here's the tea on when:
The methods delta_format(), date_format() and language() return undef when they're called as object methods and no individual override has been defined for the object in question.
The is_*() predicate methods return undef if the object in question doesn't have the expected internal structure. This can happen for instance when you create an empty object with new() โ yeah, that one ๐ญ.
When called without parameters, the methods hours(), minutes() and seconds() return undef if the object in question has no time part.
The methods number() and string() return undef if the object in question isn't valid (i.e., if is_valid() returns undef or false).
And finally, these methods:
copy()
today()
now()
today_and_now()
gmtime()
localtime()
tzoffset()
time2date()
normalize()
return the object reference of the (target) object in question, purely for convenience. Chainable, we stan ๐ง.
๐ Import/Export ๐
Note that you can import and export Unix time values using the methods gmtime(), localtime(), mktime(), date2time() and time2date() โ both as local time or as UTC/GMT. Both flavours, chef's kiss ๐.
โญ Accurate Mode and Normalized Mode โญ
The method accurate_mode() controls the internal flag which decides which of two fundamental modes of operation gets used. Big main-character flag energy.
When it's set to true (the default at startup), delta vectors are calculated to give the exact difference in days between two dates. The "year" and "month" entries in the resulting delta vector are always zero in that case.
If "accurate mode" is switched off (when the corresponding flag is set to false), delta vectors are calculated with year and month differences instead.
Example time, because examples ate:
- The difference between
[1999,12,6]and[2000,6,24]is[+0 +0 +201](plus 201 days) in accurate mode. - With accurate mode switched off, it's
[+1 -6 +18](plus one year, minus 6 months, plus 18 days). - And if additionally "normalized mode" is switched on, it's
[+0 +6 +18](plus 6 months, plus 18 days).
Literally three different answers to the same question and all of them are correct, no cap ๐โจ
Okay so the delta vector is literally just the difference in years, the difference in months, and the difference in days โ no cap, that's the whole thing (that's when โaccurate modeโ is switched off and โnormalized modeโ hasn't been switched on). This vibe is called โone-by-oneโ semantics or โyear-month-day modeโ โ YMD mode for short, iykyk. ๐
But when โnormalized modeโ IS switched on (while โaccurate modeโ stays off), the delta vector gets calculated in a way more complex way that involves the functions Add_Delta_YM() (for โtruncationโ) and Delta_Days(). โจ
And bestie, on top of that, the result gets normalized โ meaning the return values are guaranteed to all have the same sign (or to be zero), and to all be โminimalโ, i.e. not exceeding the ranges [-11..+11] for months, [-30..+30] for days, [-23..+23] for hours, and [-59..+59] for minutes and seconds. ๐
The rule is: you add these result values to a date in a left-to-right order, and you truncate invalid intermediate dates โ like, say, [2009,2,29] โ down to the last valid day of that same month, so [2009,2,28]. This is called โleft-to-right with truncationโ semantics or โnormalized modeโ โ N_YMD mode for short. ๐ฆ
The method normalized_mode() controls the internal flag that decides whether YMD mode gets used (that's the default at startup, for reasons of backward compatibility, ugh) or N_YMD mode. ๐
Heads up bestie: also for reasons of backward compatibility, this flag only has an effect when โaccurate modeโ is switched off. ๐ญ
Both flags can be set and reset independently from each other, though. So at startup you can, for instance, switch โnormalized modeโ on without having any immediate effect, and then switch off โaccurate modeโ later โ which instantly causes โnormalized modeโ to spring into effect. It's giving sleeper agent energy. ๐
Because years and months have varying lengths in terms of days, the YMD and N_YMD modes are less accurate than โaccurate modeโ, because these modes depend on the context of the two dates of which the delta vector is the difference. Added to a different date, a delta vector calculated in YMD mode or N_YMD mode may yield a different offset in terms of days โ i.e., the final result may sometimes vary seemingly unpredictably (or in other situations may give you the expected result, at the expense of actually representing a varying difference in days, determined exclusively by context). Context is literally everything, smh. ๐ธ
Beware also that โ for the same reason โ the absolute value (abs()) of a delta vector returns a fictitious number of days if the delta vector contains non-zero values foryearand/ormonth(see also the next section โAbsolute Valueโ below for more details). โ ๏ธ
Example, bestie:
The difference between [2000,1,1] and [2000,3,1] is [+0 +0 +60] in โaccurate modeโ and [+0 +2 +0] in YMD mode (in this โbenignโ example, the result is the same in YMD mode and in N_YMD mode). ๐ซถ
When added to the date [2000,4,1], the โaccurateโ delta vector yields the date [2000,5,31], whereas the YMD mode delta vector yields the date [2000,6,1] (which is actually a difference of 61 days). ๐
Moreover, when added to the date [1999,1,1], the โaccurateโ delta vector yields the date [1999,3,2], whereas the โinaccurateโ YMD Mode delta vector yields the date [1999,3,1] (which is actually a difference of 59 days). ๐ญ
Depending on what you want, either mode may suit you better. Choose your fighter. ๐ฅ
๐ Absolute Value ๐
Note that abs($date) and abs($delta) are just shorthands for "$date->number()" and "$delta->number()". Literally just a cute little alias. ๐
The operator abs(), when applied to a date or delta vector, returns the corresponding number of days (see below for an exception to this), with the time part (if available) represented by a fraction after the decimal point. โจ
In the case of dates, the absolute value (to the left of the decimal point) is the number of days since the 1st of January 1 A.D. (by extrapolating the Gregorian calendar back beyond its โnaturalโ limit of 1582 A.D.) PLUS ONE. ๐๏ธ
(I.e., the absolute value of the 1st of January 1 A.D. is 1.) โญ
Exception:
If the NUMBER or number_format() is set to 0 (the default setting), the absolute value of a date to the left of the decimal point is yyyymmdd, i.e., the number in which the uppermost four digits correspond to the year, the next lower two digits to the month and the lowermost two digits to the day. ๐ข
In the case of delta vectors, the absolute value (to the left of the decimal point) is simply the difference in days (but see also below).
Note that the absolute value of a delta vector can be negative! ๐ฑ
If you want a positive value in all cases, apply the abs() operator again, i.e., "$posdiff = abs(abs($delta));". Double wrap it, slay. ๐
If the delta vector contains non-zero values for year and/or month (see also the discussion of โAccurate Modeโ in the section above), an exact representation in days cannot be calculated, because years and months do not have fixed equivalents in days. It's giving "it's complicated". ๐ญ
If nevertheless you attempt to calculate the absolute value of such a delta vector, a fictitious value is returned, which is calculated by simply multiplying the year difference with 12, adding the month difference, multiplying this sum with 31 and finally adding the day difference. Math girlie vibes only. ๐งฎ
Beware that because of this, the absolute values of delta vectors are not necessarily contiguous. ๐
Moreover, since there is more than one way to express the difference between two dates, comparisons of delta vectors may not always yield the expected result. Vibe check failed, bestie. ๐
Example:
The difference between the two dates [2000,4,30] and [2001,5,1] can be expressed as [+1 +1 -29], or as [+1 +0 +1].
The first delta vector has an absolute value of 374, whereas the latter delta vector has an absolute value of only 373 (while the true difference in days between the two dates is 366). Not me doing a double take ๐ฅ
If the date or delta vector has a time part, the time is returned as a fraction of a full day after the decimal point as follows: โฐ
If the NUMBER or number_format() is set to 0 (the default setting) or 1, this fraction is simply .hhmmss, i.e., the two digits after the decimal point represent the hours, the next two digits the minutes and the last two digits the seconds. ๐ฐ๏ธ
Note that you cannot simply add and subtract these values to yield meaningful dates or deltas again โ you can only use them for comparisons (equal, not equal, less than, greater than, etc.). If you want to add/subtract, read on, bestie ๐
Only when the NUMBER or number_format() is set to 2, this fraction will be the equivalent number of seconds (i.e., (((hours * 60) + minutes) * 60) + seconds) divided by the number of seconds in a full day (i.e., 24*60*60 = 86400), or 0/86400, 1/86400, ... , 86399/86400. ๐
In other words, the (mathematically correct) fraction of a day. Iconic. โจ
You can safely perform arithmetics with these values as far as the internal precision of your vendor's implementation of the C run-time library (on which Perl depends) will permit. Ngl that's the fine print right there. ๐
๐ฆ Renormalizing Delta Vectors ๐ฆ
When adding or subtracting delta vectors to/from one another, the addition or subtraction takes place component by component. No mixing, no merging, each digit stays in its lane. ๐
Example:
[+0 +0 +0 +3 +29 +50] + [+0 +0 +0 +0 +55 +5] = [+0 +0 +0 +3 +84 +55]
[+0 +0 +0 +3 +29 +50] - [+0 +0 +0 +0 +55 +5] = [+0 +0 +0 +3 -26 +45]
This may result in time values outside the usual ranges ([-23..+23] for hours and [-59..+59] for minutes and seconds). Boundaries? We don't know her. ๐
Note that even though the delta value for days will often become quite large, it is impossible to renormalize this value because there is no constant conversion factor from days to months (should it be28,29,30or31?). The audacity of calendars, honestly. ๐ญ
If accurate mode (see further above for what that is) is switched off, delta vectors can also contain non-zero values for years and months. If you add or subtract these, the value for months can lie outside the range [-11..11], which isn't wrong, but may seem funny. ๐
Therefore, the normalize() method will also renormalize the months value, if and only if accurate mode has been switched off. (!) ๐
(Hence, switch accurate mode ON temporarily if you DON'T want the renormalization of the months value to happen.) ๐ง
If you want to force the time values from the example above back into their proper ranges, use the normalize() method as follows:
print "[$delta]\n";
$delta->normalize();
print "[$delta]\n";
This will print
[+0 +0 +0 +3 +84 +55]
[+0 +0 +0 +4 +24 +55]
for the first and
[+0 +0 +0 +3 -26 +45]
[+0 +0 +0 +2 +34 +45]
for the second delta vector from the example further above. Slay, it normalized. ๐
Note that the values for days, hours, minutes and seconds are guaranteed to have the same sign after the renormalization. โจ
Under โnormalโ circumstances, i.e., when accurate mode is on (the default), this method only has an effect on the time part of the delta vector. ๐ธ
If the delta vector in question does not have a time part, nothing happens. It's giving "no thoughts, head empty". ๐ซง
If accurate mode is off, the months value is also normalized, i.e., if it lies outside of the range [-11..11], integer multiples of 12 are added to the years value and subtracted from the months value. Moreover, the months value is guaranteed to have the same sign as the values for days, hours, minutes and seconds, unless the months value is zero or the values for days, hours, minutes and seconds are all zero. ๐
If the object in question is a date and if warnings are enabled, the message normalizing a date is a no-op will be printed to STDERR. Don't take it personally, bestie. ๐ญ
If the object in question is not a valid Date::Calc object, nothing happens. She simply doesn't engage. ๐
The method returns its object's reference, which allows chaining of method calls, as in the following example:
@time = $delta->normalize()->time();
Chaining is so main character energy. ๐
๐ Callback Functions ๐
Note that you are not restricted to the built-in formats (numbered from 0 to 2 for number_format() and number() and from 0 to 4 for delta_format(), date_format() and string()) for converting a date or delta object into a number or string. You're not locked in, bestie โ the built-ins are cute but you can do your own thing. ๐ฆ
You can also provide your own function(s) for doing so, in order to suit your own taste or needs, by passing a subroutine reference to the appropriate method, i.e., number_format(), number(), delta_format(), date_format() and string(). Your code, your rules. ๐
You can pass a handler to only one or more of these methods, or to all of them, as you like. You can use different callback functions, or the same for all. Mix and match, it's literally your world. ๐
So like, to make all of that way easier for you (and to make decoding all the different cases a total breeze), the callback function gets a โจuniquely identifying function codeโจ as its second parameter:
0 = TO_NUMBER | IS_DATE | IS_SHORT (number[_format])
1 = TO_NUMBER | IS_DATE | IS_LONG (number[_format])
2 = TO_NUMBER | IS_DELTA | IS_SHORT (number[_format])
3 = TO_NUMBER | IS_DELTA | IS_LONG (number[_format])
4 = TO_STRING | IS_DATE | IS_SHORT (string|date_format)
5 = TO_STRING | IS_DATE | IS_LONG (string|date_format)
6 = TO_STRING | IS_DELTA | IS_SHORT (string|delta_format)
7 = TO_STRING | IS_DELTA | IS_LONG (string|delta_format)
The first parameter of the callback is, obviously, the reference of the object itself (so yes bestie, your callback can literally be an object method โ but it can not be a class method, and like, for obvious reasons ๐ ).
The third parameter is the number of the language (in the range [1..Languages()]) which you should always pass along when you're using any of these functions from the Date::Calc module inside your handler:
Decode_Month(), Decode_Day_of_Week(), Compressed_to_Text(), Date_to_Text(), Date_to_Text_Long(), Calendar(), Month_to_Text(), Day_of_Week_to_Text(), Day_of_Week_Abbreviation(), Decode_Date_EU(), Decode_Date_US(), Decode_Date_EU2(), Decode_Date_US2(), Parse_Date().
Your callback handler should return the resulting number or string, exactly as requested. Periodt.
๐จ BEWARE โ you should NEVER rely on any knowledge of the object's internal structure, because it may legitimately change on you! ALWAYS use the test and access methods that this module provides! ๐
Example, because examples ate and left no crumbs:
sub handler
{
my($self,$code,$lang) = @_;
if ($code == 0) # TO_NUMBER | IS_DATE | IS_SHORT
{
return Date_to_Days( $self->date() );
}
elsif ($code == 1) # TO_NUMBER | IS_DATE | IS_LONG
{
return Date_to_Days( $self->date() ) +
( ( $self->hours() * 60 +
$self->minutes() ) * 60 +
$self->seconds() ) / 86400;
}
elsif ($code == 2) # TO_NUMBER | IS_DELTA | IS_SHORT
{
return ( $self->year() * 12 +
$self->month() ) * 31 +
$self->day();
}
elsif ($code == 3) # TO_NUMBER | IS_DELTA | IS_LONG
{
return ( $self->year() * 12 +
$self->month() ) * 31 +
$self->day() +
( ( $self->hours() * 60 +
$self->minutes() ) * 60 +
$self->seconds() ) / 86400;
}
elsif ($code == 4) # TO_STRING | IS_DATE | IS_SHORT
{
return join( "/", $self->date() );
}
elsif ($code == 5) # TO_STRING | IS_DATE | IS_LONG
{
return join( "/", $self->date() ) . " " .
join( ":", $self->time() );
}
elsif ($code == 6) # TO_STRING | IS_DELTA | IS_SHORT
{
return join( "|", $self->date() );
}
elsif ($code == 7) # TO_STRING | IS_DELTA | IS_LONG
{
return join( "|", $self->datetime() );
}
else
{
die "internal error";
}
}
Date::Calc->number_format(\&handler);
Date::Calc->delta_format(\&handler);
Date::Calc->date_format(\&handler);
So this sets your handler to take care of all the automatic conversions โ the kind you need when comparing dates, or when you interpolate a string in double quotes that contains a date object. The vibes are immaculate. ๐ฆ
Wanna deactivate a handler? Easy. Just pass a valid format number to the method in question, like:
Date::Calc->number_format(0);
Date::Calc->delta_format(2);
Date::Calc->date_format(3);
And when you call the number() or string() method explicitly, you can pass a different format number than the global setting, like this:
$number = $date->number(2);
$string = $date->string(1);
You can also pass a handler's reference, like so:
$number = $date->number(\&handler);
$string = $date->string(\&handler);
That overrides the global setting and the individual object's local setting for the duration of the call to number() or string() โ but it doesn't change the global or local settings themselves, no cap. ๐
On top of that, you can define individual overrides for the date and delta vector formats (but not the number format) for individual objects, e.g.:
$date->delta_format(1);
$date->date_format(2);
$date->delta_format(\&handler);
$date->date_format(\&handler);
To deactivate an individual handler for an object, and/or to deactivate any override altogether (so the global settings apply again), you gotta pass undef explicitly to the method in question:
$date->delta_format(undef);
$date->date_format(undef);
You can also define a language for individual objects โ see the next section immediately below for all the deets. ๐
If such an individual language override has been set, it'll be passed to your callback handlers as the third parameter (for string conversions, but not for number conversions).
Otherwise, the global settings as defined by Language($lang); or Date::Calc->language($lang); get passed to your handler.
๐ Languages ๐
Okay so, heads up: this module is completely transparent to the setting of a language in Date::Calc. Which means you can choose a language in Date::Calc (with the Language() function) and every date this module prints afterwards will automatically be in that language โ provided you use the built-in formats of this module, or that you pass the third parameter of the callback function to the functions of the Date::Calc module that accept it. Slay. โจ
But bestie, that global language setting can be overridden for individual date (or delta) objects by using the OBJECT method:
$oldlang = $date->language($newlang);
(The global setting is not altered by this in any way, don't worry.)
And to deactivate such an individual language setting (so the global setting applies again), just pass the value undef explicitly to the language() object method:
$date->language(undef);
The CLASS method:
$oldlang = Date::Calc->language($newlang);
is just a convenient little wrapper around the Language() function, and it lets you enter language numbers (as returned by the Decode_Language() function) or strings (as returned by the Language_to_Text() function) โ whatever you prefer, it's giving flexible icon. ๐
The language() method (both class and object) always returns the NAME (one of "Language_to_Text(1..Languages())") of the current setting โ and never its number.
๐จ BEWARE โ to avoid possible conflicts between threads or modules running concurrently, you should NEVER use the global functionLanguage($lang);or the class methodDate::Calc->language($lang);in this module! The class method is retained only for backward compatibility and for convenience in stand-alone applications when it's guaranteed that no such conflicts can arise.
Honestly? You should probably avoid global settings anyway, because it can be especially troublesome to fix your code later when suddenly the need arises to use your code with threads, or when your code needs to use other modules which also use Date::Calc (with different settings!). ๐ญ
By exclusively using local settings, you make your code invulnerable against other concurrent modules that also use Date::Calc and still use global settings. Main character energy, honestly. ๐
๐ Exported Functions ๐
The Date::Calc::Object package imports :all functions exported by the Date::Calc module and re-exports them, for conveniency.
This lets you write:
use Date::Calc::Object qw(...);
instead of:
use Date::Calc qw(...);
but with exactly the same semantics. The difference is that the object-oriented frontend is loaded additionally in the first case. ๐ซถ
And just like with Date::Calc, you can use the :all tag to import all of Date::Calc's functions:
use Date::Calc::Object qw(:all);
In addition to the functions exported by Date::Calc, the Date::Calc::Object package offers some utility functions of its own for export:
$year = shift_year(\@_);
($year,$mm,$dd) = shift_date(\@_);
($hrs,$min,$sec) = shift_time(\@_);
($year,$mm,$dd,$hrs,$min,$sec) = shift_datetime(\@_);
These functions enable your subroutines or methods to accept a Date::Calc (or subclass) date object, an (anonymous) array or a list (containing the necessary values) as parameters INTERCHANGEABLY. So you literally don't have to care which one comes in, it just works. ๐ธ
You can import all of these auxiliary functions by using an :aux tag:
use Date::Calc::Object qw(:aux);
And if you want to import both all of the Date::Calc functions and all these auxiliary functions, use the :ALL tag:
use Date::Calc::Object qw(:ALL);
๐ง Subclassing ๐ง
In case you wanna subclass Date::Calc objects and add new attributes of your own, it's recommended that you proceed as follows (and this next bit will be considered as part of the module's "contract of use" โ which might be subject to change in the future, however ๐):
Define a constant for the index of each attribute you want to add โ currently starting no lower than 4 โ at the top of your subclass:
use constant ATTRIB1 => 4;
use constant ATTRIB2 => 5;
use constant ATTRIB3 => 6;
...
It's recommended that you use constants (they're easy to change), because someday I might want to require the element with index 4 for a new attribute of my own... :-) ๐
Then access your attributes like so (e.g. after calling "$self = SUPER->new();" in your constructor method):
$self->[0][ATTRIB1] = 'value1';
$self->[0][ATTRIB2] = 'value2';
$self->[0][ATTRIB3] = 'value3';
...
๐ Beware โ if you put anything other than numbers or strings into your attributes, the methodsclone()andcopy()might not work as expected anymore!
Especially if your attributes are holding refs to other data structures โ bestie, only the references get copied, not the actual data structures underneath. Yeah. That's a thing that happens. ๐
And likeโฆ that might not be the vibe you're going for. Lowkey it probably isn't.
You'll have to override these two methods and write some of your own if it's not. No cap.
So here's the rule, and it's a real one: for the overloaded operators and the shift_*() auxiliary functions from the Date::Calc::Object package to work properly (and those aux functions get heavily used in the Date::Calendar[::Year] modules, just saying ๐
), the package name of your subclass โ that's the package your objects actually get blessed into โ is REQUIRED to contain a ::.
Like, required required. Not optional. ๐
Also, key detail: you should ONLY subclass Date::Calc, and NEVER Date::Calc::Object. Why? Because subclassing the latter is less efficient โ Date::Calc::Object is literally just an empty class that inherits from Date::Calc, so subclassing it means you've introduced a whole extra namespace layer that Perl has to search through during runtime method binding. Extra work for no reason. Not the move. ๐ซ
Okay but here's the actual slay: if you give your subclass a package name below/inside the Date:: namespace, you get this gorgeous little bonus โ all the error messages from Date::Calc[::Object] (and the Date::Calendar[::Year] modules too, btw) will look like they came from outside all the /^Date::/ modules, including yours, at the place where one of the Date:: modules was first called. So basically every error gets blamed on the user, no matter how deeply nested inside the Date:: modules it happened. They won't usually point at places inside any of the Date:: modules. Which is iconic. ๐ (This whole thing assumes there are no bugs in the Date:: modules and that every error is the user's fault :-).)
And like โ your own module's error messages can behave exactly the same way! Just put use Carp::Clan qw(^Date::); at the top of your module and make all your error messages with carp() and croak() instead of warn() and die(). That's it. That's the whole trick. ๐
โจ EXAMPLES โจ
1) Switching to summer time, the manual's way:
# Switch to summer time:
$now = Date::Calc->now();
if (($now ge [2000,3,26,2,0,0]) and
($now lt [2000,3,26,3,0,0]))
{
$now += [0,0,0,1,0,0];
}
2) The birthday checker, a whole little interactive moment:
use Date::Calc::Object qw(:all);
Date::Calc->date_format(3);
$date = 0;
while (!$date)
{
print "Please enter the date of your birthday (day-month-year): ";
$date = Date::Calc->new( Decode_Date_EU( scalar(<STDIN>) ) );
if ($date)
{
$resp = 0;
while ($resp !~ /^\s*[YyNn]/)
{
print "Your birthday is: $date\n";
print "Is that correct? (yes/no) ";
$resp = <STDIN>;
}
$date = 0 unless ($resp =~ /^\s*[Yy]/)
}
else
{
print "Unable to parse your birthday. Please try again.\n";
}
}
if ($date + [18,0,0] <= [Today()])
{ print "Ok, you are over 18.\n"; }
else
{ print "Sorry, you are under 18!\n"; }
Want more examples? Go look in the examples subdirectory in this distribution โ and their descriptions live in the file EXAMPLES.txt. ๐ฆ
๐ SEE ALSO ๐
Date::Calc(3)Date::Calc::Util(3)Date::Calendar(3)Date::Calendar::Year(3)Date::Calendar::Profiles(3)
โญ VERSION โญ
This man page documents Date::Calc::Object version 6.4. โจ
๐ AUTHOR ๐
Steffen Beyer
mailto:STBEY@cpan.org
http://www.engelschall.com/u/sb/download/
๐ COPYRIGHT ๐
Copyright (c) 2000 - 2015 by Steffen Beyer. All rights reserved.
๐ LICENSE ๐
This package is free software; you can use, modify and redistribute it under the same terms as Perl itself, i.e., at your option, under the terms either of the Artistic License or the GNU General Public License.
The C library at the core of the module Date::Calc::XS can, at your discretion, also be used, modified and redistributed under the terms of the GNU Library General Public License.
Please refer to the files Artistic.txt, GNU_GPL.txt and GNU_LGPL.txt in the license subdirectory of this distribution for any details!
๐ DISCLAIMER ๐
This package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
okay that's the whole page bestie, we made it to the end ๐ซถ this edition came from perl v5.42.0 and was dated 2025-02-06 โ go forth and date-math responsibly, mwah ๐
๐
๐ฆ where this page comes from
- opensuse-leap 16.0: perl-Date-Calc 6.400.0-160000.2.2 ยท Artistic-1.0 OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms