1Date::Calc::Object(3) User Contributed Perl DocumentationDate::Calc::Object(3)
2
3
4
6 Date::Calc::Object - Object-oriented add-on for Date::Calc with
7 overloaded operators
8
10 Make frequent things easy and infrequent or hard things possible
11
13 Note that you do NOT need to ""use Date::Calc qw(...);"" in addition to
14 this module.
15
16 Simply
17
18 use Date::Calc::Object qw(...);
19
20 INSTEAD OF
21
22 use Date::Calc qw(...);
23
24 with the same ""qw(...)"" as you would with the "Date::Calc" module,
25 and then forget about "Date::Calc::Object" altogether.
26
27 The rest of your existing code doesn't change at all.
28
29 Note also that in order to create a new date object, you do not need to
30 use
31
32 $date_object = Date::Calc::Object->new(...);
33
34 (but you may), and should use
35
36 $date_object = Date::Calc->new(...);
37
38 instead (saves you some typing and is a trifle faster).
39
41 Export tags
42 :all - all functions from Date::Calc
43 :aux - auxiliary functions shift_*
44 :ALL - both :all and :aux
45
46 Functions
47 See Date::Calc(3) for a list of available functions.
48
49 $year = shift_year(\@_);
50 ($year,$mm,$dd) = shift_date(\@_);
51 ($hrs,$min,$sec) = shift_time(\@_);
52 ($year,$mm,$dd,$hrs,$min,$sec) = shift_datetime(\@_);
53
54 Methods
55 $old = Date::Calc->accurate_mode([FLAG]);
56 $old = Date::Calc->normalized_mode([FLAG]);
57 $old = Date::Calc->number_format([NUMBER|CODEREF]);
58 $old = Date::Calc->delta_format([NUMBER|CODEREF]); # global default
59 $old = Date::Calc->date_format([NUMBER|CODEREF]); # global default
60 $old = Date::Calc->language([LANGUAGE]); # global default - DEPRECATED
61
62 $old = $date->accurate_mode([FLAG]); # is global nevertheless!
63 $old = $date->normalized_mode([FLAG]); # is global nevertheless!
64 $old = $date->number_format([NUMBER|CODEREF]); # is global nevertheless!
65 $old = $date->delta_format([NUMBER|CODEREF]); # individual override
66 $old = $date->date_format([NUMBER|CODEREF]); # individual override
67 $old = $date->language([LANGUAGE]); # individual override
68
69 $flag = $date->is_delta();
70 $flag = $date->is_date();
71 $flag = $date->is_short(); # i.e., has no time part
72 $flag = $date->is_long(); # i.e., has time part
73 $flag = $date->is_valid();
74
75 $date = Date::Calc->new([TYPE]);
76 $date = Date::Calc->new([TYPE,]YEAR,MONTH,DAY[,HRS,MIN,SEC]);
77 $date = Date::Calc->new($arrayref);
78 $newdate = $somedate->new([TYPE]);
79 $newdate = $somedate->new([TYPE,]YEAR,MONTH,DAY[,HRS,MIN,SEC]);
80 $newdate = $somedate->new($arrayref);
81
82 $datecopy = $date->clone();
83 $targetdate->copy($sourcedate);
84 $targetdate->copy($arrayref);
85 $targetdate->copy(@list);
86
87 ($year,$month,$day) = $date->date([TYPE]);
88 ($year,$month,$day) = $date->date([TYPE,]YEAR,MONTH,DAY[,HRS,MIN,SEC]);
89 ($year,$month,$day) = $date->date($arrayref);
90 ([$hrs,$min,$sec]) = $date->time([TYPE]);
91 ($hrs,$min,$sec) = $date->time([TYPE,]HRS,MIN,SEC);
92 ([$hrs,$min,$sec]) = $date->time($arrayref);
93
94 ($year,$month,$day,$hrs,$min,$sec) =
95 $date->datetime([TYPE]);
96 ($year,$month,$day,$hrs,$min,$sec) =
97 $date->datetime([TYPE,]YEAR,MONTH,DAY[,HRS,MIN,SEC]);
98
99 $date = Date::Calc->today([FLAG]);
100 $date = Date::Calc->now([FLAG]); # shorthand for --+
101 $date = Date::Calc->today_and_now([FLAG]); # <-----+
102 $date = Date::Calc->gmtime([time]); # UTC/GMT
103 $date = Date::Calc->localtime([time]); # local time
104 $delta = Date::Calc->tzoffset([time]);
105 $date = Date::Calc->time2date([time]); # UTC/GMT
106
107 $date->today([FLAG]); # updates the date part only
108 $date->now([FLAG]); # updates the time part only
109 $date->today_and_now([FLAG]); # updates both date and time
110 $date->gmtime([time]); # updates both date and time (UTC/GMT)
111 $date->localtime([time]); # updates both date and time (local time)
112 $delta->tzoffset([time]); # updates both date and time
113 $date->time2date([time]); # updates both date and time (UTC/GMT)
114
115 $time = Date::Calc->mktime(); # same as "$time = CORE::time();"
116 $time = Date::Calc->date2time(); # same as "$time = CORE::time();"
117
118 $time = $date->mktime(); # converts into Unix time (local time)
119 $time = $date->date2time(); # converts into Unix time (UTC/GMT)
120
121 $year = $date->year([YEAR]);
122 $month = $date->month([MONTH]);
123 $day = $date->day([DAY]);
124 $hours = $date->hours([HRS]);
125 $minutes = $date->minutes([MIN]);
126 $seconds = $date->seconds([SEC]);
127
128 $number = $date->number([NUMBER|CODEREF]);
129 $string = $date->string([NUMBER|CODEREF][,LANGUAGE]);
130
131 $delta->normalize(); # renormalizes a delta vector
132
133 Overloaded Operators
134 #####################################################
135 # Scalar operands are always converted into a delta #
136 # vector with that many days, i.e., [1,0,0,SCALAR] #
137 #####################################################
138
139 Comparison Operators:
140 if ($date1 < $date2) { # compares date part only
141 if ($date1 <= $date2) { # compares date part only
142 if ($date1 > $date2) { # compares date part only
143 if ($date1 >= $date2) { # compares date part only
144 if ($date1 == $date2) { # compares date part only
145 if ($date1 != $date2) { # compares date part only
146
147 $comp = $date1 <=> $date2; # compares date part only
148
149 if ($date1 lt $date2) { # compares both date and time
150 if ($date1 le $date2) { # compares both date and time
151 if ($date1 gt $date2) { # compares both date and time
152 if ($date1 ge $date2) { # compares both date and time
153 if ($date1 eq $date2) { # compares both date and time
154 if ($date1 ne $date2) { # compares both date and time
155
156 $comp = $date1 cmp $date2; # compares both date and time
157
158 Note that you can of course also compare two deltas, but not a date and
159 a delta!
160
161 ##################################################
162 # Default TYPE for array refs in comparisons is: #
163 # Same as other operand #
164 ##################################################
165
166 if ([2000,4,1] == $date) {
167 if ($today > [2000,4,1]) {
168
169 if ($now ge [2000,3,26,2,0,0]) {
170
171 if ($delta == [18,0,0]) {
172 if ($delta == -1) {
173
174 Plus:
175 $date2 = $date1 + $delta;
176 $date2 = $delta + $date1;
177 $date += $delta;
178 $this = $date++;
179 $next = ++$date;
180
181 $delta3 = $delta1 + $delta2;
182 $delta1 += $delta2;
183 $delta += $date; # beware of implicit type change!
184 $delta++;
185 ++$delta;
186
187 #####################################################
188 # Default TYPE for array refs in '+' operations is: #
189 # Opposite of other operand #
190 #####################################################
191
192 $date2 = [2000,3,26] + $delta;
193 $date2 = $date1 + [+1,0,0];
194 $date2 = [0,0,-1] + $date1;
195 $date2 = $date1 + 1;
196 $date += [0,0,+1];
197 $date += 2;
198
199 $delta3 = [1,+1,0,-1] + $delta2;
200 $delta3 = $delta1 + [1,0,0,+1];
201 $delta3 = $delta1 + 1;
202 $delta += [1,0,+1,0];
203 $delta += [2000,3,26]; # beware of implicit type change!
204 $delta += 7;
205
206 Unary Minus:
207 $delta2 = -$delta1;
208
209 Minus:
210 $delta = $date2 - $date1;
211 $date2 = $date1 - $delta;
212 $date -= $delta;
213 $date2 -= $date1; # beware of implicit type change!
214 $this = $date--;
215 $prev = --$date;
216
217 $delta3 = $delta2 - $delta1;
218 $delta2 -= $delta1;
219 $delta--;
220 --$delta;
221
222 #####################################################
223 # Default TYPE for array refs in '-' operations is: #
224 # Always a date #
225 #####################################################
226
227 $delta = $today - [2000,3,26];
228 $delta = [2000,4,1] - $date;
229 $date2 = [2000,3,26] - $delta;
230 $date2 = $date1 - [1,0,0,+7];
231 $date2 = $date1 - 7;
232 $date -= [1,0,0,+1]; # better add [0,0,-1] instead!
233 $date2 -= [2000,3,26]; # beware of implicit type change!
234 $date2 -= 1;
235
236 $delta3 = [1,0,+1,0] - $delta1;
237 $delta3 = $delta2 - [1,0,0,-1];
238 $delta -= [1,0,0,+1];
239 $delta -= 7;
240
241 Miscellaneous Operators:
242 $string = "$date";
243 $string = "$delta";
244
245 print "$date\n";
246 print "$delta\n";
247
248 if ($date) { # date is valid
249 if ($delta) { # delta is valid
250
251 $days = abs($date);
252 $diff = abs($delta); # can be negative!
253
254 $diff = abs(abs($delta)); # always positive
255
257 • FLAG
258
259 "FLAG" is either 0 (for "false") or 1 (for "true").
260
261 In the case of ""accurate_mode()"" and ""normalized_mode()"", this
262 switches the corresponding mode on and off (see further below for an
263 explanation of what these are).
264
265 In the case of ""today()"", ""now()"" and ""today_and_now()"", a
266 "true" value indicates "GMT" (Greenwich Mean Time), as opposed to
267 local time, which is the default.
268
269 • NUMBER
270
271 "NUMBER" is a number between 0 and 2 (for "number_format()" and
272 "number()") or between 0 and 4 (for "delta_format()", "date_format()"
273 and "string()"), indicating which of the three/five predefined
274 formats, respectively, should be used for converting a date into
275 numeric representation (needed for comparing dates, for instance) or
276 string representation.
277
278 Format #0 is the default at startup and the simplest of all (and
279 should be fastest to calculate, too).
280
281 The string representation of dates in format #0 also has the
282 advantage of being sortable in chronological order (and of complying
283 with ISO 8601).
284
285 (The numeric formats are (trivially) always sortable in chronological
286 order of course.)
287
288 The other formats are (mostly) increasingly more sophisticated (in
289 terms of esthetics and computation time) with increasing number
290 (except for format #4):
291
292 Delta number formats (short):
293
294 0 13603
295 1 13603
296 2 13603
297
298 Delta string formats (short):
299
300 0 '+0+0+13603'
301 1 '+0 +0 +13603'
302 2 '+0Y +0M +13603D'
303 3 '+0 Y +0 M +13603 D'
304 4 '(0,0,13603)'
305
306 Date number formats (short):
307
308 0 20010401
309 1 730576
310 2 730576
311
312 Date string formats (short):
313
314 0 '20010401'
315 1 '01-Apr-2001'
316 2 'Sun 1-Apr-2001'
317 3 'Sunday, April 1st 2001'
318 4 '[2001,4,1]'
319
320 Delta number formats (long):
321
322 0 13603.012959
323 1 13603.012959
324 2 13603.0624884259
325
326 Delta string formats (long):
327
328 0 '+0+0+13603+1+29+59'
329 1 '+0 +0 +13603 +1 +29 +59'
330 2 '+0Y +0M +13603D +1h +29m +59s'
331 3 '+0 Y +0 M +13603 D +1 h +29 m +59 s'
332 4 '(0,0,13603,1,29,59)'
333
334 Date number formats (long):
335
336 0 20010401.082959
337 1 730576.082959
338 2 730576.354155093
339
340 Date string formats (long):
341
342 0 '20010401082959'
343 1 '01-Apr-2001 08:29:59'
344 2 'Sun 1-Apr-2001 08:29:59'
345 3 'Sunday, April 1st 2001 08:29:59'
346 4 '[2001,4,1,8,29,59]'
347
348 If a number outside of the permitted range is specified, or if the
349 value is not a code reference (see also the next section below for
350 more details), the default format #0 is used instead.
351
352 • CODEREF
353
354 "CODEREF" is the reference of a subroutine which can be passed to the
355 methods "number_format()", "delta_format()" and "date_format()" in
356 order to install a callback function which will be called
357 subsequently whenever a date (or delta) object needs to be
358 (implicitly) converted into a number or string.
359
360 This happens for instance when you compare two date objects, or when
361 you put a date object reference in a string between double quotes.
362
363 Such a "CODEREF" can also be passed to the methods "number()" and
364 "string()" for explicitly converting a date object as desired.
365
366 • LANGUAGE
367
368 "LANGUAGE" is either a number in the range "[1..Languages()]", or one
369 of the strings ""Language_to_Text(1..Languages())"" (see also
370 Date::Calc(3)).
371
372 • TYPE
373
374 "TYPE" is 0 for a regular date and 1 for a delta vector (a list of
375 year, month, day and optionally hours, minutes and seconds offsets).
376
377 • Storage
378
379 "Date::Calc" objects are implemented as two nested arrays.
380
381 The "blessed" array (whose reference is the object reference you
382 receive when calling the "new()" method) contains an anonymous array
383 at position zero and the object's data in its remaining fields.
384
385 The embedded anonymous array is used for storing the object's
386 attributes (flags).
387
388 Dates and delta vectors always comprise either 3 or 6 data values:
389 Year, month, day plus (optionally) hours, minutes and seconds.
390
391 These values are stored in the "blessed" array at positions 1..3 or
392 1..6, respectively.
393
394 An object without the time values is therefore called "short", and an
395 object having time values is called "long" throughout this manual.
396
397 Hint: Whenever possible, if you do not need the time values, omit
398 them, i.e., always use the "short" form of the object if possible,
399 this will speed up calculations a little (the short form uses
400 different (faster) functions for all calculations internally).
401
402 The embedded anonymous array contains various flags:
403
404 At position zero, it contains the "TYPE" indicator which determines
405 whether the object is a date or a delta vector.
406
407 At position 1, the object stores the "NUMBER" of one of the delta
408 vector formats, or the reference of a callback function which
409 converts the contents of the object into string representation if
410 it's a delta vector, or "undef" if the global settings apply.
411
412 At position 2, the object stores the "NUMBER" of one of the date
413 formats, or the reference of a callback function which converts the
414 contents of the object into string representation if it's a date, or
415 "undef" if the global settings apply.
416
417 At position 3, the object stores the "LANGUAGE" to be used for all
418 conversions into strings (where applicable), or "undef" if the global
419 language setting applies.
420
421 Note that your callback functions (see the section "Callback
422 Functions" further below for more details) should not pay attention
423 to this value at position 3, because they get a parameter which tells
424 them which language to use (this is necessary in order to allow
425 temporary overrides).
426
427 If your callback handlers use the "*_to_Text*" functions (or any
428 other language-dependent function) from the "Date::Calc" module, your
429 handlers should pass on this language parameter to these functions
430 (and not the value from position 3).
431
432 Be reminded though that you should NEVER access the object's internal
433 data directly, i.e., through their positional numbers, but ALWAYS
434 through their respective accessor methods, e.g.:
435
436 year()
437 month()
438 day()
439 hours()
440 minutes()
441 seconds()
442 date()
443 time()
444 datetime()
445 is_delta()
446 is_date()
447 is_short()
448 is_long()
449 delta_format()
450 date_format()
451 language()
452
453 And although position 4 and onward in the embedded anonymous array is
454 currently unused, it might not stay so in future releases of this
455 module.
456
457 Therefore, in case you need more attributes in a subclass of the
458 "Date::Calc[::Object]" class, I suggest using values starting at
459 positions a bit further up, e.g. 6, 8 or 10.
460
461 • Invalid Dates
462
463 Only "new()" allows to create objects containing possibly invalid
464 dates (needed for reading in and evaluating user input, for example).
465
466 • Usage
467
468 The methods
469
470 accurate_mode()
471 normalized_mode()
472 number_format()
473 delta_format()
474 date_format()
475 language()
476 date()
477 time()
478 datetime()
479 year()
480 month()
481 day()
482 hours()
483 minutes()
484 seconds()
485
486 are used for reading as well as for setting attributes. They simply
487 return the values in question if they are called without parameters.
488
489 The methods
490
491 accurate_mode()
492 normalized_mode()
493 number_format()
494 delta_format()
495 date_format()
496 language()
497
498 always return the previous value if a new value is set. This allows
499 you to change these values temporarily and to restore their old value
500 afterwards more easily (but you can also override the "format" and
501 "language" settings directly when calling the "number()" or
502 "string()" method).
503
504 The methods
505
506 date()
507 time()
508 datetime()
509 year()
510 month()
511 day()
512 hours()
513 minutes()
514 seconds()
515
516 always return the new values when the corresponding values have been
517 changed.
518
519 The method "date()" NEVER returns the time values (hours, minutes,
520 seconds) even if they have just been set using this method (which the
521 method optionally allows). Otherwise it would be very hard to predict
522 the exact number of values it returns, which might lead to errors
523 (wrong number of parameters) elsewhere in your program.
524
525 The method "datetime()" ALWAYS returns the time values (hours,
526 minutes, seconds) even if the object in question lacks a time part.
527 In that case, zeros are returned for hours, minutes and seconds
528 instead (but the stored time part is left unchanged, whether it
529 exists or not).
530
531 If you do not provide values for hours, minutes and seconds when
532 using the method "date()" to set the values for year, month and day,
533 the time part will not be changed (whether it exists or not).
534
535 If you do not provide values for hours, minutes and seconds when
536 using the method "datetime()" to set the values for year, month and
537 day, the time part will be filled with zeros (the time part will be
538 created if necessary).
539
540 If the object is short, i.e., if it does not have any time values,
541 the method "time()" returns an empty list.
542
543 If the object is short and the methods "hours()", "minutes()" or
544 "seconds()" are used to set any of these time values, the object is
545 automatically promoted to the "long" form, and the other two time
546 values are filled with zeros.
547
548 The following methods can also return "undef" under certain
549 circumstances:
550
551 delta_format()
552 date_format()
553 language()
554 is_delta()
555 is_date()
556 is_short()
557 is_long()
558 is_valid()
559 hours()
560 minutes()
561 seconds()
562 number()
563 string()
564
565 The methods "delta_format()", "date_format()" and "language()" return
566 "undef" when they are called as object methods and no individual
567 override has been defined for the object in question.
568
569 The "is_*()" predicate methods return "undef" if the object in
570 question does not have the expected internal structure. This can
571 happen for instance when you create an empty object with "new()".
572
573 When called without parameters, the methods "hours()", "minutes()"
574 and "seconds()" return "undef" if the object in question does not
575 have a time part.
576
577 The methods "number()" and "string()" return "undef" if the object in
578 question is not valid (i.e., if "is_valid()" returns "undef" or
579 false).
580
581 And finally, the methods
582
583 copy()
584 today()
585 now()
586 today_and_now()
587 gmtime()
588 localtime()
589 tzoffset()
590 time2date()
591 normalize()
592
593 return the object reference of the (target) object in question for
594 convenience.
595
596 • Import/Export
597
598 Note that you can import and export Unix "time" values using the
599 methods "gmtime()", "localtime()", "mktime()", "date2time()" and
600 "time2date()", both as local time or as UTC/GMT.
601
602 • Accurate Mode and Normalized Mode
603
604 The method "accurate_mode()" controls the internal flag which
605 determines which of two fundamental modes of operation is used.
606
607 When set to true (the default at startup), delta vectors are
608 calculated to give the exact difference in days between two dates.
609 The "year" and "month" entries in the resulting delta vector are
610 always zero in that case.
611
612 If "accurate mode" is switched off (when the corresponding flag is
613 set to false), delta vectors are calculated with year and month
614 differences.
615
616 E.g., the difference between "[1999,12,6]" and "[2000,6,24]" is "[+0
617 +0 +201]" (plus 201 days) in accurate mode and "[+1 -6 +18]" (plus
618 one year, minus 6 months, plus 18 days) when accurate mode is
619 switched off, and is "[+0 +6 +18]" (plus 6 months, plus 18 days) if
620 additionally, "normalized mode" is switched on.
621
622 The delta vector is calculated by simply taking the difference in
623 years, the difference in months and the difference in days (if
624 "accurate mode" is switched off and if "normalized mode" has not been
625 switched on). This is called "one-by-one" semantics or "year-month-
626 day mode"; "YMD mode" for short.
627
628 When "normalized mode" is switched on (while "accurate mode" is
629 switched off), the delta vector is calculated in a more complex way
630 involving the functions ""Add_Delta_YM()"" (for "truncation") and
631 ""Delta_Days()"".
632
633 Moreover, the result is normalized, i.e., the return values are
634 guaranteed to all have the same sign (or to be zero), and to all be
635 "minimal", i.e., not to exceed the ranges "[-11..+11]" for months,
636 "[-30..+30]" for days, "[-23..+23]" for hours and "[-59..+59]" for
637 minutes and seconds.
638
639 The rule is to add these result values to a date in a left-to-right
640 order, and to truncate invalid intermediate dates, such as e.g.
641 "[2009,2,29]", to the last valid day of that same month, e.g.
642 "[2009,2,28]". This is called "left-to-right with truncation"
643 semantics or "normalized mode"; "N_YMD mode" for short.
644
645 The method "normalized_mode()" controls the internal flag which
646 determines whether "YMD mode" is used (the default at startup, for
647 reasons of backward compatibility) or "N_YMD mode".
648
649 Note that also for reasons of backward compatibility, this flag only
650 has effect when "accurate mode" is switched off.
651
652 Both flags can be set and reset independently from each other,
653 however.
654
655 Therefore, at startup, you can for instance switch "normalized mode"
656 on, without having any immediate effect, and switch off "accurate
657 mode" later, which instantly also causes "normalized mode" to spring
658 into effect.
659
660 Because years and months have varying lengths in terms of days, the
661 "YMD" and "N_YMD" modes are less accurate than "accurate mode",
662 because these modes depend on the context of the two dates of which
663 the delta vector is the difference. Added to a different date, a
664 delta vector calculated in "YMD mode" or "N_YMD mode" may yield a
665 different offset in terms of days, i.e., the final result may
666 sometimes vary seemingly unpredictably (or in other situations may
667 give you the expected result, at the expense of actually representing
668 a varying difference in days, determined exclusively by context).
669
670 Beware also that - for the same reason - the absolute value
671 (""abs()"") of a delta vector returns a fictitious number of days if
672 the delta vector contains non-zero values for "year" and/or "month"
673 (see also the next section "Absolute Value" below for more details).
674
675 Example:
676
677 The difference between "[2000,1,1]" and "[2000,3,1]" is "[+0 +0 +60]"
678 in "accurate mode" and "[+0 +2 +0]" in "YMD mode" (in this "benign"
679 example, the result is the same in "YMD mode" and in "N_YMD mode").
680
681 When added to the date "[2000,4,1]", the "accurate" delta vector
682 yields the date "[2000,5,31]", whereas the "YMD mode" delta vector
683 yields the date "[2000,6,1]" (which is actually a difference of 61
684 days).
685
686 Moreover, when added to the date "[1999,1,1]", the "accurate" delta
687 vector yields the date "[1999,3,2]", whereas the "inaccurate" "YMD
688 Mode" delta vector yields the date "[1999,3,1]" (which is actually a
689 difference of 59 days).
690
691 Depending on what you want, either mode may suit you better.
692
693 • Absolute Value
694
695 Note that ""abs($date)"" and ""abs($delta)"" are just shorthands for
696 ""$date->number()"" and ""$delta->number()"".
697
698 The operator ""abs()"", when applied to a date or delta vector,
699 returns the corresponding number of days (see below for an exception
700 to this), with the time part (if available) represented by a fraction
701 after the decimal point.
702
703 In the case of dates, the absolute value (to the left of the decimal
704 point) is the number of days since the 1st of January 1 A.D. (by
705 extrapolating the Gregorian calendar back beyond its "natural" limit
706 of 1582 A.D.) PLUS ONE.
707
708 (I.e., the absolute value of the 1st of January 1 A.D. is 1.)
709
710 Exception:
711
712 If the "NUMBER" or "number_format()" is set to 0 (the default
713 setting), the absolute value of a date to the left of the decimal
714 point is "yyyymmdd", i.e., the number in which the uppermost four
715 digits correspond to the year, the next lower two digits to the month
716 and the lowermost two digits to the day.
717
718 In the case of delta vectors, the absolute value (to the left of the
719 decimal point) is simply the difference in days (but see also below).
720
721 Note that the absolute value of a delta vector can be negative!
722
723 If you want a positive value in all cases, apply the ""abs()""
724 operator again, i.e., ""$posdiff = abs(abs($delta));"".
725
726 If the delta vector contains non-zero values for "year" and/or
727 "month" (see also the discussion of "Accurate Mode" in the section
728 above), an exact representation in days cannot be calculated, because
729 years and months do not have fixed equivalents in days.
730
731 If nevertheless you attempt to calculate the absolute value of such a
732 delta vector, a fictitious value is returned, which is calculated by
733 simply multiplying the year difference with 12, adding the month
734 difference, multiplying this sum with 31 and finally adding the day
735 difference.
736
737 Beware that because of this, the absolute values of delta vectors are
738 not necessarily contiguous.
739
740 Moreover, since there is more than one way to express the difference
741 between two dates, comparisons of delta vectors may not always yield
742 the expected result.
743
744 Example:
745
746 The difference between the two dates "[2000,4,30]" and "[2001,5,1]"
747 can be expressed as "[+1 +1 -29]", or as "[+1 +0 +1]".
748
749 The first delta vector has an absolute value of 374, whereas the
750 latter delta vector has an absolute value of only 373 (while the true
751 difference in days between the two dates is 366).
752
753 If the date or delta vector has a time part, the time is returned as
754 a fraction of a full day after the decimal point as follows:
755
756 If the "NUMBER" or "number_format()" is set to 0 (the default
757 setting) or 1, this fraction is simply ".hhmmss", i.e., the two
758 digits after the decimal point represent the hours, the next two
759 digits the minutes and the last two digits the seconds.
760
761 Note that you cannot simply add and subtract these values to yield
762 meaningful dates or deltas again, you can only use them for
763 comparisons (equal, not equal, less than, greater than, etc.). If you
764 want to add/subtract, read on:
765
766 Only when the "NUMBER" or "number_format()" is set to 2, this
767 fraction will be the equivalent number of seconds (i.e., "(((hours *
768 60) + minutes) * 60) + seconds") divided by the number of seconds in
769 a full day (i.e., "24*60*60 = 86400"), or "0/86400", "1/86400", ... ,
770 "86399/86400".
771
772 In other words, the (mathematically correct) fraction of a day.
773
774 You can safely perform arithmetics with these values as far as the
775 internal precision of your vendor's implementation of the C run-time
776 library (on which Perl depends) will permit.
777
778 • Renormalizing Delta Vectors
779
780 When adding or subtracting delta vectors to/from one another, the
781 addition or subtraction takes place component by component.
782
783 Example:
784
785 [+0 +0 +0 +3 +29 +50] + [+0 +0 +0 +0 +55 +5] = [+0 +0 +0 +3 +84 +55]
786 [+0 +0 +0 +3 +29 +50] - [+0 +0 +0 +0 +55 +5] = [+0 +0 +0 +3 -26 +45]
787
788 This may result in time values outside the usual ranges ("[-23..+23]"
789 for hours and "[-59..+59]" for minutes and seconds).
790
791 Note that even though the delta value for days will often become
792 quite large, it is impossible to renormalize this value because there
793 is no constant conversion factor from days to months (should it be
794 28, 29, 30 or 31?).
795
796 If accurate mode (see further above for what that is) is switched
797 off, delta vectors can also contain non-zero values for years and
798 months. If you add or subtract these, the value for months can lie
799 outside the range "[-11..11]", which isn't wrong, but may seem funny.
800
801 Therefore, the "normalize()" method will also renormalize the
802 "months" value, if and only if accurate mode has been switched off.
803 (!)
804
805 (Hence, switch accurate mode ON temporarily if you DON'T want the
806 renormalization of the "months" value to happen.)
807
808 If you want to force the time values from the example above back into
809 their proper ranges, use the "normalize()" method as follows:
810
811 print "[$delta]\n";
812 $delta->normalize();
813 print "[$delta]\n";
814
815 This will print
816
817 [+0 +0 +0 +3 +84 +55]
818 [+0 +0 +0 +4 +24 +55]
819
820 for the first and
821
822 [+0 +0 +0 +3 -26 +45]
823 [+0 +0 +0 +2 +34 +45]
824
825 for the second delta vector from the example further above.
826
827 Note that the values for days, hours, minutes and seconds are
828 guaranteed to have the same sign after the renormalization.
829
830 Under "normal" circumstances, i.e., when accurate mode is on (the
831 default), this method only has an effect on the time part of the
832 delta vector.
833
834 If the delta vector in question does not have a time part, nothing
835 happens.
836
837 If accurate mode is off, the "months" value is also normalized, i.e.,
838 if it lies outside of the range "[-11..11]", integer multiples of 12
839 are added to the "years" value and subtracted from the "months"
840 value. Moreover, the "months" value is guaranteed to have the same
841 sign as the values for days, hours, minutes and seconds, unless the
842 "months" value is zero or the values for days, hours, minutes and
843 seconds are all zero.
844
845 If the object in question is a date and if warnings are enabled, the
846 message "normalizing a date is a no-op" will be printed to STDERR.
847
848 If the object in question is not a valid "Date::Calc" object, nothing
849 happens.
850
851 The method returns its object's reference, which allows chaining of
852 method calls, as in the following example:
853
854 @time = $delta->normalize()->time();
855
856 • Callback Functions
857
858 Note that you are not restricted to the built-in formats (numbered
859 from 0 to 2 for "number_format()" and "number()" and from 0 to 4 for
860 "delta_format()", "date_format()" and "string()") for converting a
861 date or delta object into a number or string.
862
863 You can also provide your own function(s) for doing so, in order to
864 suit your own taste or needs, by passing a subroutine reference to
865 the appropriate method, i.e., "number_format()", "number()",
866 "delta_format()", "date_format()" and "string()".
867
868 You can pass a handler to only one or more of these methods, or to
869 all of them, as you like. You can use different callback functions,
870 or the same for all.
871
872 In order to facilitate the latter, and in order to make the decoding
873 of the various cases easier for you, the callback function receives a
874 uniquely identifying function code as its second parameter:
875
876 0 = TO_NUMBER | IS_DATE | IS_SHORT (number[_format])
877 1 = TO_NUMBER | IS_DATE | IS_LONG (number[_format])
878 2 = TO_NUMBER | IS_DELTA | IS_SHORT (number[_format])
879 3 = TO_NUMBER | IS_DELTA | IS_LONG (number[_format])
880 4 = TO_STRING | IS_DATE | IS_SHORT (string|date_format)
881 5 = TO_STRING | IS_DATE | IS_LONG (string|date_format)
882 6 = TO_STRING | IS_DELTA | IS_SHORT (string|delta_format)
883 7 = TO_STRING | IS_DELTA | IS_LONG (string|delta_format)
884
885 The first parameter of the callback function is of course the
886 reference of the object in question itself (therefore, the callback
887 function can actually be an object method - but not a class method,
888 for obvious reasons).
889
890 The third parameter is the number of the language (in the range
891 "[1..Languages()]") which you should always pass along when using any
892 of the following functions from the "Date::Calc" module in your
893 handler:
894
895 "Decode_Month()", "Decode_Day_of_Week()", "Compressed_to_Text()",
896 "Date_to_Text()", "Date_to_Text_Long()", "Calendar()",
897 "Month_to_Text()", "Day_of_Week_to_Text()",
898 "Day_of_Week_Abbreviation()", "Decode_Date_EU()", "Decode_Date_US()",
899 "Decode_Date_EU2()", "Decode_Date_US2()", "Parse_Date()".
900
901 The callback handler should return the resulting number or string, as
902 requested.
903
904 BEWARE that you should NEVER rely upon any knowledge of the object's
905 internal structure, as this may be subject to change!
906
907 ALWAYS use the test and access methods provided by this module!
908
909 Example:
910
911 sub handler
912 {
913 my($self,$code,$lang) = @_;
914
915 if ($code == 0) # TO_NUMBER | IS_DATE | IS_SHORT
916 {
917 return Date_to_Days( $self->date() );
918 }
919 elsif ($code == 1) # TO_NUMBER | IS_DATE | IS_LONG
920 {
921 return Date_to_Days( $self->date() ) +
922 ( ( $self->hours() * 60 +
923 $self->minutes() ) * 60 +
924 $self->seconds() ) / 86400;
925 }
926 elsif ($code == 2) # TO_NUMBER | IS_DELTA | IS_SHORT
927 {
928 return ( $self->year() * 12 +
929 $self->month() ) * 31 +
930 $self->day();
931 }
932 elsif ($code == 3) # TO_NUMBER | IS_DELTA | IS_LONG
933 {
934 return ( $self->year() * 12 +
935 $self->month() ) * 31 +
936 $self->day() +
937 ( ( $self->hours() * 60 +
938 $self->minutes() ) * 60 +
939 $self->seconds() ) / 86400;
940 }
941 elsif ($code == 4) # TO_STRING | IS_DATE | IS_SHORT
942 {
943 return join( "/", $self->date() );
944 }
945 elsif ($code == 5) # TO_STRING | IS_DATE | IS_LONG
946 {
947 return join( "/", $self->date() ) . " " .
948 join( ":", $self->time() );
949 }
950 elsif ($code == 6) # TO_STRING | IS_DELTA | IS_SHORT
951 {
952 return join( "|", $self->date() );
953 }
954 elsif ($code == 7) # TO_STRING | IS_DELTA | IS_LONG
955 {
956 return join( "|", $self->datetime() );
957 }
958 else
959 {
960 die "internal error";
961 }
962 }
963
964 Date::Calc->number_format(\&handler);
965 Date::Calc->delta_format(\&handler);
966 Date::Calc->date_format(\&handler);
967
968 This sets our handler to take care of all automatic conversions, such
969 as needed when comparing dates or when interpolating a string in
970 double quotes which contains a date object.
971
972 To deactivate a handler, simply pass a valid format number to the
973 method in question, e.g.:
974
975 Date::Calc->number_format(0);
976 Date::Calc->delta_format(2);
977 Date::Calc->date_format(3);
978
979 When calling the "number()" or "string()" method explicitly, you can
980 pass a different format number (than the global setting), like this:
981
982 $number = $date->number(2);
983 $string = $date->string(1);
984
985 You can also pass a handler's reference, like so:
986
987 $number = $date->number(\&handler);
988 $string = $date->string(\&handler);
989
990 This overrides the global setting and the individual object's local
991 setting for the duration of the call of "number()" or "string()" (but
992 doesn't change the global or local settings themselves).
993
994 Moreover, you can also define individual overrides for the date and
995 the delta vector formats (but not the number format) for individual
996 objects, e.g.:
997
998 $date->delta_format(1);
999 $date->date_format(2);
1000
1001 $date->delta_format(\&handler);
1002 $date->date_format(\&handler);
1003
1004 In order to deactivate an individual handler for an object, and/or in
1005 order to deactivate any override altogether (so that the global
1006 settings apply again), you have to pass "undef" explicitly to the
1007 method in question:
1008
1009 $date->delta_format(undef);
1010 $date->date_format(undef);
1011
1012 You can also define a language for individual objects (see the next
1013 section immediately below for more details).
1014
1015 If such an individual language override has been set, it will be
1016 passed to your callback handlers as the third parameter (in the case
1017 of "string" conversions, but not in the case of "number"
1018 conversions).
1019
1020 Otherwise, the global settings as defined by "Language($lang);" or
1021 "Date::Calc-"language($lang);> will be passed to your handler.
1022
1023 • Languages
1024
1025 Note that this module is completely transparent to the setting of a
1026 language in "Date::Calc". This means that you can choose a language
1027 in "Date::Calc" (with the "Language()" function) and all dates
1028 subsequently printed by this module will automatically be in that
1029 language - provided that you use the built-in formats of this module,
1030 or that you pass the third parameter of the callback funtion to the
1031 funtions of the "Date::Calc" module which accept it.
1032
1033 However, this global language setting can be overridden for
1034 individual date (or delta) objects by using the OBJECT method
1035
1036 $oldlang = $date->language($newlang);
1037
1038 (The global setting is not altered by this in any way.)
1039
1040 In order to deactivate such an individual language setting (so that
1041 the global setting applies again), simply pass the value "undef"
1042 explicitly to the "language()" object method:
1043
1044 $date->language(undef);
1045
1046 The CLASS method
1047
1048 $oldlang = Date::Calc->language($newlang);
1049
1050 is just a convenient wrapper around the "Language()" function, which
1051 allows you to enter language numbers (as returned by the
1052 "Decode_Language()" function) or strings (as returned by the
1053 "Language_to_Text()" function), whatever you prefer.
1054
1055 The "language()" method (both class and object) always returns the
1056 NAME (one of ""Language_to_Text(1..Languages())"") of the current
1057 setting (and never its number).
1058
1059 BEWARE that in order to avoid possible conflicts between threads or
1060 modules running concurrently, you should NEVER use the global
1061 function "Language($lang);" or the class method
1062 "Date::Calc-"language($lang);> in this module!
1063
1064 The class method is retained only for backward compatibility and for
1065 convenience in stand-alone applications when it is guaranteed that no
1066 such conflicts can arise.
1067
1068 But you should probably avoid to use global settings anyway, because
1069 it may be especially troublesome to fix your code later when suddenly
1070 the need arises to use your code with threads or when your code needs
1071 to use other modules which also use "Date::Calc" (with different
1072 settings!).
1073
1074 By exclusively using local settings, you are making your code
1075 invulnerable against other, concurrent modules also using
1076 "Date::Calc" which still use global settings.
1077
1078 • Exported Functions
1079
1080 The "Date::Calc::Object" package imports ":all" functions exported by
1081 the "Date::Calc" module and re-exports them, for conveniency.
1082
1083 This allows you to write
1084
1085 use Date::Calc::Object qw(...);
1086
1087 instead of
1088
1089 use Date::Calc qw(...);
1090
1091 but with exactly the same semantics. The difference is that the
1092 object-oriented frontend is loaded additionally in the first case.
1093
1094 As with "Date::Calc" you can use the ":all" tag to import all of
1095 "Date::Calc"'s functions:
1096
1097 use Date::Calc::Object qw(:all);
1098
1099 In addition to the functions exported by "Date::Calc", the
1100 "Date::Calc::Object" package offers some utility functions of its own
1101 for export:
1102
1103 $year = shift_year(\@_);
1104 ($year,$mm,$dd) = shift_date(\@_);
1105 ($hrs,$min,$sec) = shift_time(\@_);
1106 ($year,$mm,$dd,$hrs,$min,$sec) = shift_datetime(\@_);
1107
1108 These functions enable your subroutines or methods to accept a
1109 "Date::Calc" (or subclass) date object, an (anonymous) array or a
1110 list (containing the necessary values) as parameters INTERCHANGEABLY.
1111
1112 You can import all of these auxiliary functions by using an ":aux"
1113 tag:
1114
1115 use Date::Calc::Object qw(:aux);
1116
1117 If you want to import both all of the "Date::Calc" functions as well
1118 as all these auxiliary functions, use the ":ALL" tag:
1119
1120 use Date::Calc::Object qw(:ALL);
1121
1122 • Subclassing
1123
1124 In case you want to subclass "Date::Calc" objects and to add new
1125 attributes of your own, it is recommended that you proceed as follows
1126 (the following will be considered as a part of the module's "contract
1127 of use" - which might be subject to change in the future, however):
1128
1129 Define a constant for the index of each attribute you want to add,
1130 currently starting no lower than "4", at the top of your subclass:
1131
1132 use constant ATTRIB1 => 4;
1133 use constant ATTRIB2 => 5;
1134 use constant ATTRIB3 => 6;
1135 ...
1136
1137 It is recommended that you use constants (which are easy to change),
1138 because I someday might want to require the element with index "4"
1139 for a new attribute of my own... ":-)"
1140
1141 Then access your attributes like so (e.g. after calling ""$self =
1142 SUPER->new();"" in your constructor method):
1143
1144 $self->[0][ATTRIB1] = 'value1';
1145 $self->[0][ATTRIB2] = 'value2';
1146 $self->[0][ATTRIB3] = 'value3';
1147 ...
1148
1149 Beware that if you put anything other than numbers or strings into
1150 your attributes, the methods "clone()" and "copy()" might not work as
1151 expected anymore!
1152
1153 Especially if your attributes contain references to other data
1154 structures, only the references will be copied, but not the data
1155 structures themselves.
1156
1157 This may not be what you want.
1158
1159 (You will have to override these two methods and write some of your
1160 own if not.)
1161
1162 In order for the overloaded operators and the "shift_*()" auxiliary
1163 functions from the "Date::Calc::Object" package to work properly (the
1164 latter of which are heavily used in the "Date::Calendar[::Year]"
1165 modules, for instance), the package name of your subclass (= the one
1166 your objects will be blessed into) is REQUIRED to contain a "::".
1167
1168 Note that you should ONLY subclass "Date::Calc", NEVER
1169 "Date::Calc::Object", since subclassing the latter is less efficient
1170 (because "Date::Calc::Object" is just an empty class which inherits
1171 from "Date::Calc" - subclassing "Date::Calc::Object" would thus just
1172 introduce an additional name space layer to search during Perl's
1173 runtime method binding process).
1174
1175 If you give your subclass a package name below/inside the "Date::"
1176 namespace, you will also benefit from the fact that all error
1177 messages produced by the "Date::Calc[::Object]" module (and also the
1178 "Date::Calendar[::Year]" modules, by the way) will appear to have
1179 originated from the place outside of all ""/^Date::/"" modules
1180 (including yours) where one of the "Date::" modules was first called
1181 - i.e., all errors are always blamed on the user, no matter how
1182 deeply nested inside the "Date::" modules they occur, and do not
1183 usually refer to places inside any of the "Date::" modules (this
1184 assumes that there are no bugs in the "Date::" modules, and that all
1185 errors are always the user's fault ":-)").
1186
1187 Moreover, your module's own error messages will behave in the same
1188 way if you ""use Carp::Clan qw(^Date::);"" at the top of your module
1189 and if you produce all error messages using "carp()" and "croak()"
1190 (instead of "warn()" and "die()", respectively).
1191
1193 1)
1194 # Switch to summer time:
1195 $now = Date::Calc->now();
1196 if (($now ge [2000,3,26,2,0,0]) and
1197 ($now lt [2000,3,26,3,0,0]))
1198 {
1199 $now += [0,0,0,1,0,0];
1200 }
1201
1202 2)
1203 use Date::Calc::Object qw(:all);
1204
1205 Date::Calc->date_format(3);
1206
1207 $date = 0;
1208 while (!$date)
1209 {
1210 print "Please enter the date of your birthday (day-month-year): ";
1211 $date = Date::Calc->new( Decode_Date_EU( scalar(<STDIN>) ) );
1212 if ($date)
1213 {
1214 $resp = 0;
1215 while ($resp !~ /^\s*[YyNn]/)
1216 {
1217 print "Your birthday is: $date\n";
1218 print "Is that correct? (yes/no) ";
1219 $resp = <STDIN>;
1220 }
1221 $date = 0 unless ($resp =~ /^\s*[Yy]/)
1222 }
1223 else
1224 {
1225 print "Unable to parse your birthday. Please try again.\n";
1226 }
1227 }
1228
1229 if ($date + [18,0,0] <= [Today()])
1230 { print "Ok, you are over 18.\n"; }
1231 else
1232 { print "Sorry, you are under 18!\n"; }
1233
1234 For more examples, see the "examples" subdirectory in this
1235 distribution, and their descriptions in the file "EXAMPLES.txt".
1236
1238 Date::Calc(3), Date::Calc::Util(3), Date::Calendar(3),
1239 Date::Calendar::Year(3), Date::Calendar::Profiles(3).
1240
1242 This man page documents "Date::Calc::Object" version 6.4.
1243
1245 Steffen Beyer
1246 mailto:STBEY@cpan.org
1247 http://www.engelschall.com/u/sb/download/
1248
1250 Copyright (c) 2000 - 2015 by Steffen Beyer. All rights reserved.
1251
1253 This package is free software; you can use, modify and redistribute it
1254 under the same terms as Perl itself, i.e., at your option, under the
1255 terms either of the "Artistic License" or the "GNU General Public
1256 License".
1257
1258 The C library at the core of the module "Date::Calc::XS" can, at your
1259 discretion, also be used, modified and redistributed under the terms of
1260 the "GNU Library General Public License".
1261
1262 Please refer to the files "Artistic.txt", "GNU_GPL.txt" and
1263 "GNU_LGPL.txt" in the "license" subdirectory of this distribution for
1264 any details!
1265
1267 This package is distributed in the hope that it will be useful, but
1268 WITHOUT ANY WARRANTY; without even the implied warranty of
1269 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1270
1271 See the "GNU General Public License" for more details.
1272
1273
1274
1275perl v5.34.0 2021-07-22 Date::Calc::Object(3)