Date::...:Object(3pm)
π¦ Date::...:Object(3pm) π¦
okay bestie, welcome to the User Contributed Perl Documentation page for Date::...:Object(3pm). yes the name is a whole mystery, yes it's a lot, but we're doing this together. this is part 1 of 5 so don't go anywhere π
π NAME π
Date::Pcalc::Object β the object-oriented add-on for Date::Pcalc, and it comes with overloaded operators β¨
π₯ MOTTO π₯
Make frequent things easy and infrequent or hard things possible
that's the whole motto. iconic. moving on π
π« PREFACE π«
okay so listen, the very first thing: you do NOT need to ""use Date::Pcalc qw(...);"" on top of this module. no ma'am.
You simply do
use Date::Pcalc::Object qw(...);
INSTEAD OF
use Date::Pcalc qw(...);
with the exact same qw(...) you'd normally use with the Date::Pcalc module, and then you justβ¦ forget Date::Pcalc::Object exists altogether. it's giving "set it and forget it" π§
The rest of your existing code doesn't change at all. not one bit. slay.
Also note β¨ β to create a new date object, you do not need to write
$date_object = Date::Pcalc::Object->new(...);
(though you may, if that's your vibe), and you should instead write
$date_object = Date::Pcalc->new(...);
because it saves you some typing and is a trifle faster πββοΈπ¨
β¨ SYNOPSIS β¨
π Export tags
:all - all functions from Date::Pcalc
:aux - auxiliary functions shift_*
:ALL - both :all and :aux
π Functions
See Date::Pcalc(3) for the full 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::Pcalc->accurate_mode([FLAG]);
$old = Date::Pcalc->normalized_mode([FLAG]);
$old = Date::Pcalc->number_format([NUMBER|CODEREF]);
$old = Date::Pcalc->delta_format([NUMBER|CODEREF]); # global default
$old = Date::Pcalc->date_format([NUMBER|CODEREF]); # global default
$old = Date::Pcalc->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::Pcalc->new([TYPE]);
$date = Date::Pcalc->new([TYPE,]YEAR,MONTH,DAY[,HRS,MIN,SEC]);
$date = Date::Pcalc->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::Pcalc->today([FLAG]);
$date = Date::Pcalc->now([FLAG]); # shorthand for --+
$date = Date::Pcalc->today_and_now([FLAG]); # <-----+
$date = Date::Pcalc->gmtime([time]); # UTC/GMT
$date = Date::Pcalc->localtime([time]); # local time
$delta = Date::Pcalc->tzoffset([time]);
$date = Date::Pcalc->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::Pcalc->mktime(); # same as "$time = CORE::time();"
$time = Date::Pcalc->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
FLAG is either 0 (for "false") or 1 (for "true"). simple as that π
In the case of accurate_mode() and normalized_mode(), this switches the corresponding mode on and off (see further below for an explanation of what these are).
In the case of today(), now() and today_and_now(), a true value indicates GMT (Greenwich Mean Time), as opposed to local time, which is the default.
NUMBER
NUMBER is a number between 0 and 2 (for number_format() and number()) or between 0 and 4 (for delta_format(), date_format() and string()), 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 it just keeps going, bestie, so buckle up π
First up, this batch of formats:
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 +59 s'4β'(0,0,13603,1,29,59)'
Date number formats (long):
0β20010401.0829591β730576.0829592β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]'
If a number outside of the permitted range is specified, or if the value is not a code reference (see also the next section below for more details), the default format #0 is used instead. no cap, it just quietly ignores you and uses #0 π
CODEREFβ this is the reference of a subroutine, and you can hand it over to the methodsnumber_format(),delta_format()anddate_format()to install a callback function. That callback then gets called every single time a date (or delta) object needs to be (implicitly) converted into a number or a string. β¨
This happens, for instance, when you compare two date objects, or when you drop a date object reference into a string between double quotes. π«Ά
And yes, you can also pass such a CODEREF to the methods number() and string() to explicitly convert a date object however you want. slay.
LANGUAGEβ either a number in the range[1..Languages()], or one of the strings"Language_to_Text(1..Languages())"(see alsoDate::Pcalc(3)).TYPEβ0for a regular date πΈ and1for a delta vector (which is a list of year, month, day and optionally hours, minutes and seconds offsets).- Storage β okay so
Date::Pcalcobjects are implemented as two nested arrays.
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.
These 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 the time values is called "long" throughout this manual.
Hint: whenever possible, if you do not need the time values, omit them β like, always use the "short" form of the object if you can. It speeds up calculations a little (the short form uses different, faster functions for all calculations internally). lowkey free performance ποΈβ¨
The embedded anonymous array contains various flags:
- At position zero, it contains the
TYPEindicator, which decides whether the object is a date or a delta vector. - At position 1, the object stores the
NUMBERof one of the delta vector formats, or the reference of a callback function which converts the contents of the object into a string representation if it's a delta vector, orundefif the global settings apply. - At position 2, the object stores the
NUMBERof one of the date formats, or the reference of a callback function which converts the contents of the object into a string representation if it's a date, orundefif the global settings apply. - At position 3, the object stores the
LANGUAGEto be used for all conversions into strings (where applicable), orundefif the global language setting applies.
Note that your callback functions (peep the section "Callback Functions" further below for more details π) should not pay attention to this value at position 3, because they get a parameter which tells them which language to use (this is necessary in order to allow temporary overrides).
If your callback handlers use the *_to_Text* functions (or any other language-dependent function) from the Date::Pcalc module, your handlers should pass on this language parameter to these functions β and not the value from position 3.
Be reminded though that you should NEVER access the object's internal data directly, i.e., through their positional numbers, but ALWAYS through their respective accessor methods, like:
year()
month()
day()
hours()
minutes()
seconds()
date()
time()
datetime()
is_delta()
is_date()
is_short()
is_long()
delta_format()
date_format()
language()
And although position 4 and onward in the embedded anonymous array is currently unused, it might not stay so in future releases of this module. π
So if you need more attributes in a subclass of the Date::Pcalc[::Object] class, I suggest using values starting at positions a bit further up, like 6, 8 or 10. π
- Invalid Dates β only
new()allows you to create objects containing possibly invalid dates (which you need for reading in and evaluating user input, for example). - Usage β the 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 as well as for setting attributes. They just return the values in question when you call them with no parameters. π«Ά
The 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 (but you can also override the format and language settings directly when calling the number() or string() method, iykyk).
The methods
date()
time()
datetime()
year()
month()
day()
hours()
minutes()
seconds()
always return the new values when the corresponding values have been changed.
The method date() NEVER returns the time values (hours, minutes, seconds) even if they've just been set using this method (which the method optionally allows). Otherwise it would be really hard to predict the exact number of values it returns, which might lead to errors (wrong number of parameters) elsewhere in your program. π
The method datetime() ALWAYS returns the time values (hours, minutes, seconds) even if the object in question lacks a time part. In that case, zeros are returned for hours, minutes and seconds instead (but the stored time part is left unchanged, whether it exists or not).
If you don't provide values for hours, minutes and seconds when using the method date() to set the values for 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 using the method datetime() to set the values for year, month and day, the time part will be filled with zeros (and the time part will be created if necessary).
If the object is short, i.e., if it doesn't have any 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 are filled with zeros. β¨ glow up β¨
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()
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(). π
When called without parameters, the methods hours(), minutes() and seconds() return undef if the object in question doesn't have a time part.
The methods number() and string() return undef if the object in question is not valid (i.e., if is_valid() returns undef or false).
And finally, the methods
copy()
today()
now()
today_and_now()
gmtime()
localtime()
tzoffset()
time2date()
normalize()
return the object reference of the (target) object in question, just for convenience. π«Ά
- Import/Export β note that you can import and export Unix
timevalues using the methodsgmtime(),localtime(),mktime(),date2time()andtime2date(), both as local time or as UTC/GMT. π - Accurate Mode and Normalized Mode β the method
accurate_mode()controls the internal flag which determines which of two fundamental modes of operation is used.
When it's set to true (which is 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.
E.g., the difference between [1999,12,6] and [2000,6,24] is [+0 +0 +201] (plus 201 days) in accurate mode, and [+1 -6 +18] (plus one year, minus 6 months, plus 18 days) when accurate mode is switched off β and it's [+0 +6 +18] (plus 6 months, plus 18 days) if additionally, "normalized mode" is switched on. π¦
The delta vector is literally just the difference in years, the difference in months, and the difference in days β easy math, no notes β as long as "accurate mode" is switched off and "normalized mode" hasn't been turned on. This is called "one-by-one" semantics, or "year-month-day mode", aka "YMD mode" for when you're in a hurry π
When "normalized mode" is on (and "accurate mode" is still off), the delta vector gets calculated in a way more complicated way, involving the functions Add_Delta_YM() (for the "truncation" part) and Delta_Days().
On top of that, the result gets normalized, which means the return values are guaranteed to all have the same sign (or to be zero), and to all be "minimal" β i.e. they won't exceed the ranges [-11..+11] for months, [-30..+30] for days, [-23..+23] for hours and [-59..+59] for minutes and seconds. Baby ranges, honestly.
The rule is that you add these result values to a date in a left-to-right order, and you truncate any invalid intermediate dates β like, say, [2009,2,29] β down to the last valid day of that same month, e.g. [2009,2,28]. This is called "left-to-right with truncation" semantics, or "normalized mode", aka "N_YMD mode" β¨
The method normalized_mode() controls the internal flag that decides whether "YMD mode" gets used (that's the default at startup, for backward-compatibility reasons) or "N_YMD mode".
Heads up bestie: also for backward-compatibility reasons, this flag only has any effect when "accurate mode" is switched off. π
Both flags can be set and reset independently of each other, though. So at startup you could, for instance, switch "normalized mode" on without anything immediately happening, and then switch off "accurate mode" later β which instantly makes "normalized mode" spring into effect. It was just waiting for its moment, iconic behaviour honestly.
Because years and months have varying lengths in terms of days, "YMD" and "N_YMD" modes are less accurate than "accurate mode", because these modes depend on the context of the two dates that the delta vector is the difference of. Add a delta vector calculated in "YMD mode" or "N_YMD mode" to a different date and it may give you a different offset in terms of days β meaning the final result can sometimes vary seemingly unpredictably. (Or, in other situations, it gives you the result you expected, but at the cost of actually representing a varying difference in days that's determined exclusively by context. Pick your poison, girlie.)
Beware also that β for the very same reason β the absolute value (abs()) of a delta vector returns a fictitious number of days if the delta vector contains non-zero values for "year" and/or "month" (see also the next section, "Absolute Value", below for more on that).
Example, because I know you want one:
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" little example, the result comes out 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 π
And, 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 actually want, either mode may suit you better. There's no wrong answer, just different answers π
β¨ Absolute Value β¨
Quick note: abs($date) and abs($delta) are just shorthands for $date->number() and $delta->number().
The operator abs(), when you apply it to a date or a delta vector, returns the corresponding number of days (with an exception, see below), with the time part (if there is one) 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. β and no, that's not a typo, we're 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.)
Chapter exception, though:
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 where 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).
Bestie, note that the absolute value of a delta vector can be negative! π
If you want a positive value in all cases, just apply the abs() operator again, i.e. $posdiff = abs(abs($delta));.
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. They're just out here being 28 days sometimes, whatever.
If you nevertheless attempt to calculate the absolute value of such a delta vector, a fictitious value is returned, which gets calculated by simply multiplying the year difference with 12, adding the month difference, multiplying this sum with 31, and finally adding the day difference.
Beware that because of this, the absolute values of delta vectors are not necessarily contiguous. And on top of that, since there's more than one way to express the difference between two dates, comparisons of delta vectors may not always yield the result you expected π
Example, since you asked:
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. Numbers were harmed in the making of this example πΈ
If the date or delta vector has a time part, the time comes back as a fraction of a full day after the decimal point, like this:
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 get 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: π
Only when the NUMBER or number_format() is set to 2 does this fraction become 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. Slay.
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. So like, go off, but within reason.
π¦ Renormalizing Delta Vectors π¦
When you add or subtract delta vectors to/from one another, the addition or subtraction happens component by component.
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 sneaking outside the usual ranges ([-23..+23] for hours and [-59..+59] for minutes and seconds). Rude of them.
Note that even though the delta value for days will often become quite large, it is impossible to renormalize this value, because there's no constant conversion factor from days to months. Should it be 28, 29, 30 or 31? Nobody knows! Not even the calendar π
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 those, the value for months can lie outside the range [-11..11], which isn't wrong exactly, but it may seem a little funny.
So, the normalize() method will also renormalize the "months" value β if and only if accurate mode has been switched off. (!) Yes, that (!) is doing a lot of work.
(Hence: switch accurate mode ON temporarily if you DON'T want the renormalization of the "months" value to happen. Sneaky little trick, we love her.)
If you want to force the time values from the example above back into their proper ranges, use the normalize() method like this:
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 one, and
[+0 +0 +0 +3 -26 +45]
[+0 +0 +0 +2 +34 +45]
for the second delta vector from the example further above. Look at those ranges snapping right back into place π
Note that the values for days, hours, minutes and seconds are guaranteed to all have the same sign after the renormalization.
Under "normal" circumstances β i.e. when accurate mode is on (which is the default) β this method only has an effect on the time part of the delta vector.
If the delta vector in question doesn't have a time part, nothing happens. Nothing! At all! π«Ά
If accurate mode is off, the "months" value also gets 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. Details matter, bestie.
If the object in question is a date and warnings are enabled, the message normalizing a date is a no-op will be printed to STDERR. It's giving "you tried" energy and I respect it.
If the object in question is not a valid Date::Pcalc object, nothing happens. Again. Nothing. π§
The method returns its object's reference, which lets you chain method calls, like in this example:
@time = $delta->normalize()->time();
Chain it, queen. π
π 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 a string.
You can also bring your own function(s) to do it β 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().
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 for each, or the same function for all of them. Fully your call, no rules here besides the cool ones β¨
In order to facilitate the latter, and in order to make the decoding of the various cases easier for you, the callback function receives 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 function is of course the reference of the object in question itself π (so yes bestie, your callback function can totally be an object method β but not a class method, for obvious reasons, no cap).
The third parameter is the number of the language (in the range "[1..Languages()]") which you should always pass along when using any of the following functions from the Date::Pcalc module in 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().
The callback handler should return the resulting number or string, as requested β¨
β οΈ BEWARE that you should NEVER rely upon any knowledge of the object's internal structure, as this may be subject to change! π
ALWAYS use the test and access methods provided by this module! π
Example:
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::Pcalc->number_format(\&handler);
Date::Pcalc->delta_format(\&handler);
Date::Pcalc->date_format(\&handler);
This sets our handler to take care of all automatic conversions, such as needed when comparing dates or when interpolating a string in double quotes which contains a date object π¦
To deactivate a handler, simply pass a valid format number to the method in question, e.g.:
Date::Pcalc->number_format(0);
Date::Pcalc->delta_format(2);
Date::Pcalc->date_format(3);
When calling 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);
This overrides the global setting and the individual object's local setting for the duration of the call of number() or string() (but doesn't change the global or local settings themselves, okay? it's giving temporary, not permanent π«Ά).
Moreover, you can also define individual overrides for the date and the delta vector formats (but not the number format, bestie, don't try it) for individual objects, e.g.:
$date->delta_format(1);
$date->date_format(2);
$date->delta_format(\&handler);
$date->date_format(\&handler);
In order to deactivate an individual handler for an object, and/or in order to deactivate any override altogether (so that the global settings apply again), you have to 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 more details π).
If such an individual language override has been set, it will be passed to your callback handlers as the third parameter (in the case of string conversions, but not in the case of number conversions).
Otherwise, the global settings as defined by Language($lang); or Date::Pcalc-"language($lang);> will be passed to your handler.
πΈ Languages
Note that this module is completely transparent to the setting of a language in Date::Pcalc π Which means: you can choose a language in Date::Pcalc (with the Language() function) and all dates subsequently printed by this module will automatically be in that language β provided that 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::Pcalc module which accept it. Iconic behaviour, honestly β¨
However, this 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.)
In order to deactivate such an individual language setting (so that the global setting applies again), simply pass the value undef explicitly to the language() object method:
$date->language(undef);
The CLASS method
$oldlang = Date::Pcalc->language($newlang);
is just a convenient wrapper around the Language() function, which allows you to enter language numbers (as returned by the Decode_Language() function) or strings (as returned by the Language_to_Text() function), whatever you prefer πββοΈ
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 that in order to avoid possible conflicts between threads or modules running concurrently, you should NEVER use the global functionLanguage($lang);or the class methodDate::Pcalc-"language($lang);>in this module!
The class method is retained only for backward compatibility and for convenience in stand-alone applications when it is guaranteed that no such conflicts can arise.
But you should probably avoid to use global settings anyway, because it may 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::Pcalc (with different settings! π).
By exclusively using local settings, you are making your code invulnerable against other, concurrent modules also using Date::Pcalc which still use global settings π‘οΈβ¨
π Exported Functions
The Date::Pcalc::Object package imports :all functions exported by the Date::Pcalc module and re-exports them, for conveniency.
This allows you to write
use Date::Pcalc::Object qw(...);
instead of
use Date::Pcalc qw(...);
but with exactly the same semantics (fr fr, no behavioural difference). The difference is that the object-oriented frontend is loaded additionally in the first case.
As with Date::Pcalc you can use the :all tag to import all of Date::Pcalc's functions:
use Date::Pcalc::Object qw(:all);
In addition to the functions exported by Date::Pcalc, the Date::Pcalc::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::Pcalc (or subclass) date object, an (anonymous) array or a list (containing the necessary values) as parameters INTERCHANGEABLY π¦
You can import all of these auxiliary functions by using an :aux tag:
use Date::Pcalc::Object qw(:aux);
If you want to import both all of the Date::Pcalc functions as well as all these auxiliary functions, use the :ALL tag:
use Date::Pcalc::Object qw(:ALL);
π Subclassing
In case you want to subclass Date::Pcalc objects and to add new attributes of your own, it is recommended that you proceed as follows (the following will be considered as a 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 is recommended that you use constants (which are easy to change), because I someday 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 that if you put anything other than numbers or strings into your attributes, the methodsclone()andcopy()might not work as expected anymore!
Okay so, like, especially if your attributes contain references to other data structures, only the references will be copied, but not the data structures themselves. π
This may not be what you want. π
(You will have to override these two methods and write some of your own if not. No pressure, bestie.)
In order for the overloaded operators and the shift_*() auxiliary functions from the Date::Pcalc::Object package to work properly (the latter of which are heavily used in the Date::Pcalendar[::Year] modules, for instance), the package name of your subclass (= the one your objects will be blessed into) is REQUIRED to contain a ::. Periodt. π
Note that you should ONLY subclass Date::Pcalc, NEVER Date::Pcalc::Object, since subclassing the latter is less efficient (because Date::Pcalc::Object is just an empty class which inherits from Date::Pcalc - subclassing Date::Pcalc::Object would thus just introduce an additional name space layer to search during Perl's runtime method binding process). It's giving unnecessary drama. π
If you give your subclass a package name below/inside the Date:: namespace, you will also benefit from the fact that all error messages produced by the Date::Pcalc[::Object] module (and also the Date::Pcalendar[::Year] modules, by the way) will appear to have originated from the place outside of all ""/^Date::/"" modules (including yours) where one of the Date:: modules was first called - i.e., all errors are always blamed on the user, no matter how deeply nested inside the Date:: modules they occur, and do not usually refer to places inside any of the Date:: modules (this assumes that there are no bugs in the Date:: modules, and that all errors are always the user's fault ":-)"). Iconic behavior, honestly. π
Moreover, your module's own error messages will behave in the same way if you ""use Carp::Clan qw(^Date::);"" at the top of your module and if you produce all error messages using carp() and croak() (instead of warn() and die(), respectively). Slay. π
β¨ EXAMPLES β¨
- Switch to summer time:
# Switch to summer time:
$now = Date::Pcalc->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.
use Date::Pcalc::Object qw(:all);
Date::Pcalc->date_format(3);
$date = 0;
while (!$date)
{
print "Please enter the date of your birthday (day-month-year): ";
$date = Date::Pcalc->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"; }
For more examples, see the examples subdirectory in this distribution, and their descriptions in the file EXAMPLES.txt. π¦
π SEE ALSO π
Date::Pcalc(3)Date::Calc::Util(3)Date::Pcalendar(3)Date::Pcalendar::Year(3)Date::Pcalendar::Profiles(3)
π VERSION π
This man page documents Date::Pcalc::Object version 6.1.
π AUTHOR π
- Steffen Beyer
mailto:STBEY@cpan.orghttp://www.engelschall.com/u/sb/download/
π COPYRIGHT π
Copyright (c) 2000 - 2009 by Steffen Beyer. All rights reserved.
π LICENSE π
This package is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e., under the terms of the "Artistic License" or the "GNU General Public License".
Please refer to the files "Artistic.txt" and "GNU_GPL.txt" in this distribution for 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.
And that's the tea! This page was generated from Perl v5.42.3 on 2026-08-20, and it's the man page for Date::...:Object(3pm). Stay slaying, bestie! πβ¨π«Ά
π¦ where this page comes from
- ubuntu stonking: libdate-pcalc-perl 6.1-8build1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms