1DateTime(3) User Contributed Perl Documentation DateTime(3)
2
3
4
6 DateTime - A date and time object for Perl
7
9 version 1.54
10
12 use DateTime;
13
14 $dt = DateTime->new(
15 year => 1964,
16 month => 10,
17 day => 16,
18 hour => 16,
19 minute => 12,
20 second => 47,
21 nanosecond => 500000000,
22 time_zone => 'Asia/Taipei',
23 );
24
25 $dt = DateTime->from_epoch( epoch => $epoch );
26 $dt = DateTime->now; # same as ( epoch => time )
27
28 $year = $dt->year;
29 $month = $dt->month; # 1-12
30
31 $day = $dt->day; # 1-31
32
33 $dow = $dt->day_of_week; # 1-7 (Monday is 1)
34
35 $hour = $dt->hour; # 0-23
36 $minute = $dt->minute; # 0-59
37
38 $second = $dt->second; # 0-61 (leap seconds!)
39
40 $doy = $dt->day_of_year; # 1-366 (leap years)
41
42 $doq = $dt->day_of_quarter; # 1..
43
44 $qtr = $dt->quarter; # 1-4
45
46 # all of the start-at-1 methods above have corresponding start-at-0
47 # methods, such as $dt->day_of_month_0, $dt->month_0 and so on
48
49 $ymd = $dt->ymd; # 2002-12-06
50 $ymd = $dt->ymd('/'); # 2002/12/06
51
52 $mdy = $dt->mdy; # 12-06-2002
53 $mdy = $dt->mdy('/'); # 12/06/2002
54
55 $dmy = $dt->dmy; # 06-12-2002
56 $dmy = $dt->dmy('/'); # 06/12/2002
57
58 $hms = $dt->hms; # 14:02:29
59 $hms = $dt->hms('!'); # 14!02!29
60
61 $is_leap = $dt->is_leap_year;
62
63 # these are localizable, see Locales section
64 $month_name = $dt->month_name; # January, February, ...
65 $month_abbr = $dt->month_abbr; # Jan, Feb, ...
66 $day_name = $dt->day_name; # Monday, Tuesday, ...
67 $day_abbr = $dt->day_abbr; # Mon, Tue, ...
68
69 # May not work for all possible datetime, see the docs on this
70 # method for more details.
71 $epoch_time = $dt->epoch;
72
73 $dt2 = $dt + $duration_object;
74
75 $dt3 = $dt - $duration_object;
76
77 $duration_object = $dt - $dt2;
78
79 $dt->set( year => 1882 );
80
81 $dt->set_time_zone('America/Chicago');
82
83 $dt->set_formatter($formatter);
84
86 DateTime is a class for the representation of date/time combinations,
87 and is part of the Perl DateTime project. For details on this project
88 please see <http://datetime.perl.org/>. The DateTime site has a FAQ
89 which may help answer many "how do I do X?" questions. The FAQ is at
90 <http://datetime.perl.org/wiki/datetime/page/FAQ>.
91
92 It represents the Gregorian calendar, extended backwards in time before
93 its creation (in 1582). This is sometimes known as the "proleptic
94 Gregorian calendar". In this calendar, the first day of the calendar
95 (the epoch), is the first day of year 1, which corresponds to the date
96 which was (incorrectly) believed to be the birth of Jesus Christ.
97
98 The calendar represented does have a year 0, and in that way differs
99 from how dates are often written using "BCE/CE" or "BC/AD".
100
101 For infinite datetimes, please see the DateTime::Infinite module.
102
104 0-based Versus 1-based Numbers
105 The "DateTime" module follows a simple logic for determining whether or
106 not a given number is 0-based or 1-based.
107
108 Month, day of month, day of week, and day of year are 1-based. Any
109 method that is 1-based also has an equivalent 0-based method ending in
110 "_0". So for example, this class provides both "day_of_week" and
111 "day_of_week_0" methods.
112
113 The "day_of_week_0" method still treats Monday as the first day of the
114 week.
115
116 All time-related numbers such as hour, minute, and second are 0-based.
117
118 Years are neither, as they can be both positive or negative, unlike any
119 other datetime component. There is a year 0.
120
121 There is no "quarter_0" method.
122
123 Error Handling
124 Some errors may cause this module to die with an error string. This can
125 only happen when calling constructor methods, methods that change the
126 object, such as "set", or methods that take parameters. Methods that
127 retrieve information about the object, such as "year" or "epoch", will
128 never die.
129
130 Locales
131 All the object methods which return names or abbreviations return data
132 based on a locale. This is done by setting the locale when constructing
133 a DateTime object. If this is not set, then "en-US" is used.
134
135 Floating DateTimes
136 The default time zone for new DateTime objects, except where stated
137 otherwise, is the "floating" time zone. This concept comes from the
138 iCal standard. A floating datetime is one which is not anchored to any
139 particular time zone. In addition, floating datetimes do not include
140 leap seconds, since we cannot apply them without knowing the datetime's
141 time zone.
142
143 The results of date math and comparison between a floating datetime and
144 one with a real time zone are not really valid, because one includes
145 leap seconds and the other does not. Similarly, the results of datetime
146 math between two floating datetimes and two datetimes with time zones
147 are not really comparable.
148
149 If you are planning to use any objects with a real time zone, it is
150 strongly recommended that you do not mix these with floating datetimes.
151
152 Math
153 If you are going to be doing date math, please read the section "How
154 DateTime Math Works".
155
156 Determining the Local Time Zone Can Be Slow
157 If $ENV{TZ} is not set, it may involve reading a number of files in
158 /etc or elsewhere. If you know that the local time zone won't change
159 while your code is running, and you need to make many objects for the
160 local time zone, it is strongly recommended that you retrieve the local
161 time zone once and cache it:
162
163 our $App::LocalTZ = DateTime::TimeZone->new( name => 'local' );
164
165 # then everywhere else
166
167 my $dt = DateTime->new( ..., time_zone => $App::LocalTZ );
168
169 DateTime itself does not do this internally because local time zones
170 can change, and there's no good way to determine if it's changed
171 without doing all the work to look it up.
172
173 Far Future DST
174 Do not try to use named time zones (like "America/Chicago") with dates
175 very far in the future (thousands of years). The current implementation
176 of "DateTime::TimeZone" will use a huge amount of memory calculating
177 all the DST changes from now until the future date. Use UTC or the
178 floating time zone and you will be safe.
179
180 Globally Setting a Default Time Zone
181 Warning: This is very dangerous. Do this at your own risk!
182
183 By default, "DateTime" uses either the floating time zone or UTC for
184 newly created objects, depending on the constructor.
185
186 You can force "DateTime" to use a different time zone by setting the
187 "PERL_DATETIME_DEFAULT_TZ" environment variable.
188
189 As noted above, this is very dangerous, as it affects all code that
190 creates a "DateTime" object, including modules from CPAN. If those
191 modules expect the normal default, then setting this can cause
192 confusing breakage or subtly broken data. Before setting this variable,
193 you are strongly encouraged to audit your CPAN dependencies to see how
194 they use "DateTime". Try running the test suite for each dependency
195 with this environment variable set before using this in production.
196
197 Upper and Lower Bounds
198 Internally, dates are represented the number of days before or after
199 0001-01-01. This is stored as an integer, meaning that the upper and
200 lower bounds are based on your Perl's integer size ($Config{ivsize}).
201
202 The limit on 32-bit systems is around 2^29 days, which gets you to year
203 (+/-)1,469,903. On a 64-bit system you get 2^62 days, to year
204 (+/-)12,626,367,463,883,278 (12.626 quadrillion).
205
207 DateTime provides many methods. The documentation breaks them down into
208 groups based on what they do (constructor, accessors, modifiers, etc.).
209
210 Constructors
211 All constructors can die when invalid parameters are given.
212
213 Warnings
214
215 Currently, constructors will warn if you try to create a far future
216 DateTime (year >= 5000) with any time zone besides floating or UTC.
217 This can be very slow if the time zone has future DST transitions that
218 need to be calculated. If the date is sufficiently far in the future
219 this can be really slow (minutes).
220
221 All warnings from DateTime use the "DateTime" category and can be
222 suppressed with:
223
224 no warnings 'DateTime';
225
226 This warning may be removed in the future if DateTime::TimeZone is made
227 much faster.
228
229 DateTime->new( ... )
230
231 my $dt = DateTime->new(
232 year => 1966,
233 month => 10,
234 day => 25,
235 hour => 7,
236 minute => 15,
237 second => 47,
238 nanosecond => 500000000,
239 time_zone => 'America/Chicago',
240 );
241
242 This class method accepts the following parameters:
243
244 • year
245
246 An integer year for the DateTime. This can be any integer number
247 within the valid range for your system (See "Upper and Lower
248 Bounds"). This is required.
249
250 • month
251
252 An integer from 1-12. Defaults to 1.
253
254 • day
255
256 An integer from 1-31. The value will be validated based on the
257 month, to prevent creating invalid dates like February 30. Defaults
258 to 1.
259
260 • hour
261
262 An integer from 0-23. Hour 0 is midnight at the beginning of the
263 given date. Defaults to 0.
264
265 • minute
266
267 An integer from 0-59. Defaults to 0.
268
269 • second
270
271 An integer from 0-61. Values of 60 or 61 are only allowed when the
272 specified date and time have a leap second. Defaults to 0.
273
274 • nanosecond
275
276 An integer that is greater than or equal to 0. If this number is
277 greater than 1 billion, it will be normalized into the second value
278 for the DateTime object. Defaults to 0
279
280 • locale
281
282 A string containing a locale code, like "en-US" or "zh-Hant-TW", or
283 an object returned by "DateTime::Locale->load". See the
284 DateTime::Locale documentation for details. Defaults to the value
285 of "DateTime->DefaultLocale", or "en-US" if the class default has
286 not been set.
287
288 • time_zone
289
290 A string containing a time zone name like "America/Chicago" or a
291 DateTime::TimeZone object. Defaults to the value of
292 $ENV{PERL_DATETIME_DEFAULT_TZ} or "floating" if that env var is not
293 set. See "Globally Setting a Default Time Zone" for more details on
294 that env var (and why you should not use it).
295
296 A string will simply be passed to the "DateTime::TimeZone->new"
297 method as its "name" parameter. This string may be an Olson DB time
298 zone name ("America/Chicago"), an offset string ("+0630"), or the
299 words "floating" or "local". See the "DateTime::TimeZone"
300 documentation for more details.
301
302 • formatter
303
304 An object or class name with a "format_datetime" method. This will
305 be used to stringify the DateTime object. This is optional. If it
306 is not specified, then stringification calls "$self->iso8601".
307
308 Invalid parameter types (like an array reference) will cause the
309 constructor to die.
310
311 Parsing Dates
312
313 This module does not parse dates! That means there is no constructor to
314 which you can pass things like "March 3, 1970 12:34".
315
316 Instead, take a look at the various DateTime::Format::*
317 <https://metacpan.org/search?q=datetime%3A%3Aformat> modules on CPAN.
318 These parse all sorts of different date formats, and you're bound to
319 find something that can handle your particular needs.
320
321 Ambiguous Local Times
322
323 Because of Daylight Saving Time, it is possible to specify a local time
324 that is ambiguous. For example, in the US in 2003, the transition from
325 to saving to standard time occurred on October 26, at 02:00:00 local
326 time. The local clock changed from 01:59:59 (saving time) to 01:00:00
327 (standard time). This means that the hour from 01:00:00 through
328 01:59:59 actually occurs twice, though the UTC time continues to move
329 forward.
330
331 If you specify an ambiguous time, then the latest UTC time is always
332 used, in effect always choosing standard time. In this case, you can
333 simply subtract an hour from the object in order to move to saving
334 time, for example:
335
336 # This object represent 01:30:00 standard time
337 my $dt = DateTime->new(
338 year => 2003,
339 month => 10,
340 day => 26,
341 hour => 1,
342 minute => 30,
343 second => 0,
344 time_zone => 'America/Chicago',
345 );
346
347 print $dt->hms; # prints 01:30:00
348
349 # Now the object represent 01:30:00 saving time
350 $dt->subtract( hours => 1 );
351
352 print $dt->hms; # still prints 01:30:00
353
354 Alternately, you could create the object with the UTC time zone and
355 then call the "set_time_zone" method to change the time zone. This is a
356 good way to ensure that the time is not ambiguous.
357
358 Invalid Local Times
359
360 Another problem introduced by Daylight Saving Time is that certain
361 local times just do not exist. For example, in the US in 2003, the
362 transition from standard to saving time occurred on April 6, at the
363 change to 2:00:00 local time. The local clock changed from 01:59:59
364 (standard time) to 03:00:00 (saving time). This means that there is no
365 02:00:00 through 02:59:59 on April 6!
366
367 Attempting to create an invalid time currently causes a fatal error.
368
369 DateTime->from_epoch( epoch => $epoch, ... )
370
371 This class method can be used to construct a new DateTime object from
372 an epoch time instead of components. Just as with the "new" method, it
373 accepts "time_zone", "locale", and "formatter" parameters.
374
375 If the epoch value is a non-integral value, it will be rounded to
376 nearest microsecond.
377
378 By default, the returned object will be in the UTC time zone.
379
380 DateTime->now( ... )
381
382 This class method is equivalent to calling "from_epoch" with the value
383 returned from Perl's "time" function. Just as with the "new" method, it
384 accepts "time_zone" and "locale" parameters.
385
386 By default, the returned object will be in the UTC time zone.
387
388 If you want sub-second resolution, use the DateTime::HiRes module's
389 "DateTime::HiRes->now" method instead.
390
391 DateTime->today( ... )
392
393 This class method is equivalent to:
394
395 DateTime->now(@_)->truncate( to => 'day' );
396
397 DateTime->last_day_of_month( ... )
398
399 This constructor takes the same arguments as can be given to the "new"
400 method, except for "day". Additionally, both "year" and "month" are
401 required.
402
403 DateTime->from_day_of_year( ... )
404
405 This constructor takes the same arguments as can be given to the "new"
406 method, except that it does not accept a "month" or "day" argument.
407 Instead, it requires both "year" and "day_of_year". The day of year
408 must be between 1 and 366, and 366 is only allowed for leap years.
409
410 DateTime->from_object( object => $object, ... )
411
412 This class method can be used to construct a new DateTime object from
413 any object that implements the "utc_rd_values" method. All
414 "DateTime::Calendar" modules must implement this method in order to
415 provide cross-calendar compatibility. This method accepts a "locale"
416 and "formatter" parameter
417
418 If the object passed to this method has a "time_zone" method, that is
419 used to set the time zone of the newly created "DateTime" object.
420
421 Otherwise, the returned object will be in the floating time zone.
422
423 $dt->clone
424
425 This object method returns a new object that is replica of the object
426 upon which the method is called.
427
428 "Get" Methods
429 This class has many methods for retrieving information about an object.
430
431 $dt->year
432
433 Returns the year.
434
435 $dt->ce_year
436
437 Returns the year according to the BCE/CE numbering system. The year
438 before year 1 in this system is year -1, aka "1 BCE".
439
440 $dt->era_name
441
442 Returns the long name of the current era, something like "Before
443 Christ". See the "Locales" section for more details.
444
445 $dt->era_abbr
446
447 Returns the abbreviated name of the current era, something like "BC".
448 See the "Locales" section for more details.
449
450 $dt->christian_era
451
452 Returns a string, either "BC" or "AD", according to the year.
453
454 $dt->secular_era
455
456 Returns a string, either "BCE" or "CE", according to the year.
457
458 $dt->year_with_era
459
460 Returns a string containing the year immediately followed by the
461 appropriate era abbreviation, based on the object's locale. The year is
462 the absolute value of "ce_year", so that year 1 is "1" and year 0 is
463 "1BC". See the "Locales" section for more details.
464
465 $dt->year_with_christian_era
466
467 Like "year_with_era", but uses the "christian_era" method to get the
468 era name.
469
470 $dt->year_with_secular_era
471
472 Like "year_with_era", but uses the "secular_era" method to get the era
473 name.
474
475 $dt->month
476
477 Returns the month of the year, from 1..12.
478
479 Also available as "$dt->mon".
480
481 $dt->month_name
482
483 Returns the name of the current month. See the "Locales" section for
484 more details.
485
486 $dt->month_abbr
487
488 Returns the abbreviated name of the current month. See the "Locales"
489 section for more details.
490
491 $dt->day
492
493 Returns the day of the month, from 1..31.
494
495 Also available as "$dt->mday" and "$dt->day_of_month".
496
497 $dt->day_of_week
498
499 Returns the day of the week as a number, from 1..7, with 1 being Monday
500 and 7 being Sunday.
501
502 Also available as "$dt->wday" and "$dt->dow".
503
504 $dt->local_day_of_week
505
506 Returns the day of the week as a number, from 1..7. The day
507 corresponding to 1 will vary based on the locale. See the "Locales"
508 section for more details.
509
510 $dt->day_name
511
512 Returns the name of the current day of the week. See the "Locales"
513 section for more details.
514
515 $dt->day_abbr
516
517 Returns the abbreviated name of the current day of the week. See the
518 "Locales" section for more details.
519
520 $dt->day_of_year
521
522 Returns the day of the year.
523
524 Also available as "$dt->doy".
525
526 $dt->quarter
527
528 Returns the quarter of the year, from 1..4.
529
530 $dt->quarter_name
531
532 Returns the name of the current quarter. See the "Locales" section for
533 more details.
534
535 $dt->quarter_abbr
536
537 Returns the abbreviated name of the current quarter. See the "Locales"
538 section for more details.
539
540 $dt->day_of_quarter
541
542 Returns the day of the quarter.
543
544 Also available as "$dt->doq".
545
546 $dt->weekday_of_month
547
548 Returns a number from 1..5 indicating which week day of the month this
549 is. For example, June 9, 2003 is the second Monday of the month, and so
550 this method returns 2 for that date.
551
552 $dt->ymd($optional_separator), $dt->mdy(...), $dt->dmy(...)
553
554 Each method returns the year, month, and day, in the order indicated by
555 the method name. Years are zero-padded to four digits. Months and days
556 are 0-padded to two digits.
557
558 By default, the values are separated by a dash (-), but this can be
559 overridden by passing a value to the method.
560
561 The "$dt->ymd" method is also available as "$dt->date".
562
563 $dt->hour
564
565 Returns the hour of the day, from 0..23.
566
567 $dt->hour_1
568
569 Returns the hour of the day, from 1..24.
570
571 $dt->hour_12
572
573 Returns the hour of the day, from 1..12.
574
575 $dt->hour_12_0
576
577 Returns the hour of the day, from 0..11.
578
579 $dt->am_or_pm
580
581 Returns the appropriate localized abbreviation, depending on the
582 current hour.
583
584 $dt->minute
585
586 Returns the minute of the hour, from 0..59.
587
588 Also available as "$dt->min".
589
590 $dt->second
591
592 Returns the second, from 0..61. The values 60 and 61 are used for leap
593 seconds.
594
595 Also available as "$dt->sec".
596
597 $dt->fractional_second
598
599 Returns the second, as a real number from 0.0 until 61.999999999
600
601 The values 60 and 61 are used for leap seconds.
602
603 $dt->millisecond
604
605 Returns the fractional part of the second as milliseconds (1E-3
606 seconds).
607
608 Half a second is 500 milliseconds.
609
610 This value will always be rounded down to the nearest integer.
611
612 $dt->microsecond
613
614 Returns the fractional part of the second as microseconds (1E-6
615 seconds).
616
617 Half a second is 500,000 microseconds.
618
619 This value will always be rounded down to the nearest integer.
620
621 $dt->nanosecond
622
623 Returns the fractional part of the second as nanoseconds (1E-9
624 seconds).
625
626 Half a second is 500,000,000 nanoseconds.
627
628 $dt->hms($optional_separator)
629
630 Returns the hour, minute, and second, all zero-padded to two digits.
631 If no separator is specified, a colon (:) is used by default.
632
633 Also available as "$dt->time".
634
635 $dt->datetime($optional_separator)
636
637 This method is equivalent to:
638
639 $dt->ymd('-') . 'T' . $dt->hms(':')
640
641 The $optional_separator parameter allows you to override the separator
642 between the date and time, for e.g. "$dt->datetime(q{ })".
643
644 This method is also available as "$dt->iso8601", but it's not really a
645 very good ISO8601 format, as it lacks a time zone. If called as
646 "$dt->iso8601" you cannot change the separator, as ISO8601 specifies
647 that "T" must be used to separate them.
648
649 $dt->rfc3339
650
651 This formats a datetime in RFC3339 format. This is the same as
652 "$dt->datetime" with an added offset at the end of the string except if
653 the time zone is the floating time zone.
654
655 If the offset is '+00:00' then this is represented as 'Z'. Otherwise
656 the offset is formatted with a leading sign (+/-) and a colon separated
657 numeric offset with hours and minutes. If the offset has a non-zero
658 seconds component, that is also included.
659
660 $dt->stringify
661
662 This method returns a stringified version of the object. It is also how
663 stringification overloading is implemented. If the object has a
664 formatter, then its "format_datetime" method is used to produce a
665 string. Otherwise, this method calls "$dt->iso8601" to produce a
666 string. See "Formatters And Stringification" for details.
667
668 $dt->is_leap_year
669
670 This method returns a boolean value indicating whether or not the
671 datetime object is in a leap year.
672
673 $dt->is_last_day_of_month
674
675 This method returns a boolean value indicating whether or not the
676 datetime object is the last day of the month.
677
678 $dt->is_last_day_of_quarter
679
680 This method returns a boolean value indicating whether or not the
681 datetime object is the last day of the quarter.
682
683 $dt->is_last_day_of_year
684
685 This method returns a boolean value indicating whether or not the
686 datetime object is the last day of the year.
687
688 $dt->month_length
689
690 This method returns the number of days in the current month.
691
692 $dt->quarter_length
693
694 This method returns the number of days in the current quarter.
695
696 $dt->year_length
697
698 This method returns the number of days in the current year.
699
700 $dt->week
701
702 my ( $week_year, $week_number ) = $dt->week;
703
704 Returns information about the calendar week for the date. The values
705 returned by this method are also available separately through the
706 "$dt->week_year" and "$dt->week_number" methods.
707
708 The first week of the year is defined by ISO as the one which contains
709 the fourth day of January, which is equivalent to saying that it's the
710 first week to overlap the new year by at least four days.
711
712 Typically the week year will be the same as the year that the object is
713 in, but dates at the very beginning of a calendar year often end up in
714 the last week of the prior year, and similarly, the final few days of
715 the year may be placed in the first week of the next year.
716
717 $dt->week_year
718
719 Returns the year of the week. See "$dt->week" for details.
720
721 $dt->week_number
722
723 Returns the week of the year, from 1..53. See "$dt->week" for details.
724
725 $dt->week_of_month
726
727 The week of the month, from 0..5. The first week of the month is the
728 first week that contains a Thursday. This is based on the ICU
729 definition of week of month, and correlates to the ISO8601 week of year
730 definition. A day in the week before the week with the first Thursday
731 will be week 0.
732
733 $dt->jd, $dt->mjd
734
735 These return the Julian Day and Modified Julian Day, respectively. The
736 value returned is a floating point number. The fractional portion of
737 the number represents the time portion of the datetime.
738
739 The Julian Day is a count of days since the beginning of the Julian
740 Period, which starts with day 0 at noon on January 1, -4712.
741
742 The Modified Julian Day is a count of days since midnight on November
743 17, 1858.
744
745 These methods always refer to the local time, so the Julian Day is the
746 same for a given datetime regardless of its time zone. Or in other
747 words, 2020-12-04T13:01:57 in "America/Chicago" has the same Julian Day
748 as 2020-12-04T13:01:57 in "Asia/Taipei".
749
750 $dt->time_zone
751
752 This returns the DateTime::TimeZone object for the datetime object.
753
754 $dt->offset
755
756 This returns the offset from UTC, in seconds, of the datetime object's
757 time zone.
758
759 $dt->is_dst
760
761 Returns a boolean indicating whether or not the datetime's time zone is
762 currently in Daylight Saving Time or not.
763
764 $dt->time_zone_long_name
765
766 This is a shortcut for "$dt->time_zone->name". It's provided so that
767 one can use "%{time_zone_long_name}" as a strftime format specifier.
768
769 $dt->time_zone_short_name
770
771 This method returns the time zone abbreviation for the current time
772 zone, such as "PST" or "GMT". These names are not definitive, and
773 should not be used in any application intended for general use by users
774 around the world. That's because it's possible for multiple time zones
775 to have the same abbreviation.
776
777 $dt->strftime( $format, ... )
778
779 This method implements functionality similar to the "strftime" method
780 in C. However, if given multiple format strings, then it will return
781 multiple scalars, one for each format string.
782
783 See the "strftime Patterns" section for a list of all possible strftime
784 patterns.
785
786 If you give a pattern that doesn't exist, then it is simply treated as
787 text.
788
789 Note that any deviation from the POSIX standard is probably a bug.
790 DateTime should match the output of "POSIX::strftime" for any given
791 pattern.
792
793 $dt->format_cldr( $format, ... )
794
795 This method implements formatting based on the CLDR date patterns. If
796 given multiple format strings, then it will return multiple scalars,
797 one for each format string.
798
799 See the "CLDR Patterns" section for a list of all possible CLDR
800 patterns.
801
802 If you give a pattern that doesn't exist, then it is simply treated as
803 text.
804
805 $dt->epoch
806
807 Returns the UTC epoch value for the datetime object. Datetimes before
808 the start of the epoch will be returned as a negative number.
809
810 The return value from this method is always an integer number of
811 seconds.
812
813 Since the epoch does not account for leap seconds, the epoch time for
814 1972-12-31T23:59:60 (UTC) is exactly the same as that for
815 1973-01-01T00:00:00.
816
817 $dt->hires_epoch
818
819 Returns the epoch as a floating point number. The floating point
820 portion of the value represents the nanosecond value of the object.
821 This method is provided for compatibility with the "Time::HiRes"
822 module.
823
824 Note that this method suffers from the imprecision of floating point
825 numbers, and the result may end up rounded to an arbitrary degree
826 depending on your platform.
827
828 my $dt = DateTime->new( year => 2012, nanosecond => 4 );
829 say $dt->hires_epoch;
830
831 On my system, this simply prints 1325376000 because adding 0.000000004
832 to 1325376000 returns 1325376000.
833
834 $dt->is_finite, $dt->is_infinite
835
836 These methods allow you to distinguish normal datetime objects from
837 infinite ones. Infinite datetime objects are documented in
838 DateTime::Infinite.
839
840 $dt->utc_rd_values
841
842 Returns the current UTC Rata Die days, seconds, and nanoseconds as a
843 three element list. This exists primarily to allow other calendar
844 modules to create objects based on the values provided by this object.
845
846 $dt->local_rd_values
847
848 Returns the current local Rata Die days, seconds, and nanoseconds as a
849 three element list. This exists for the benefit of other modules which
850 might want to use this information for date math, such as
851 DateTime::Event::Recurrence.
852
853 $dt->leap_seconds
854
855 Returns the number of leap seconds that have happened up to the
856 datetime represented by the object. For floating datetimes, this always
857 returns 0.
858
859 $dt->utc_rd_as_seconds
860
861 Returns the current UTC Rata Die days and seconds purely as seconds.
862 This number ignores any fractional seconds stored in the object, as
863 well as leap seconds.
864
865 $dt->locale
866
867 Returns the datetime's DateTime::Locale object.
868
869 $dt->formatter
870
871 Returns the current formatter object or class. See "Formatters And
872 Stringification" for details.
873
874 "Set" Methods
875 The remaining methods provided by "DateTime", except where otherwise
876 specified, return the object itself, thus making method chaining
877 possible. For example:
878
879 my $dt = DateTime->now->set_time_zone( 'Australia/Sydney' );
880
881 my $first = DateTime
882 ->last_day_of_month( year => 2003, month => 3 )
883 ->add( days => 1 )
884 ->subtract( seconds => 1 );
885
886 $dt->set( .. )
887
888 This method can be used to change the local components of a date time.
889 This method accepts any parameter allowed by the "new" method except
890 for "locale" or "time_zone". Use "set_locale" and "set_time_zone" for
891 those instead.
892
893 This method performs parameter validation just like the "new" method.
894
895 Do not use this method to do date math. Use the "add" and "subtract"
896 methods instead.
897
898 $dt->set_year, $dt->set_month, etc.
899
900 DateTime has a "set_*" method for every item that can be passed to the
901 constructor:
902
903 • $dt->set_year
904
905 • $dt->set_month
906
907 • $dt->set_day
908
909 • $dt->set_hour
910
911 • $dt->set_minute
912
913 • $dt->set_second
914
915 • $dt->set_nanosecond
916
917 These are shortcuts to calling "set" with a single key. They all take a
918 single parameter.
919
920 $dt->truncate( to => ... )
921
922 This method allows you to reset some of the local time components in
923 the object to their "zero" values. The "to" parameter is used to
924 specify which values to truncate, and it may be one of "year",
925 "quarter", "month", "week", "local_week", "day", "hour", "minute", or
926 "second".
927
928 For example, if "month" is specified, then the local day becomes 1, and
929 the hour, minute, and second all become 0.
930
931 If "week" is given, then the datetime is set to the Monday of the week
932 in which it occurs, and the time components are all set to 0. If you
933 truncate to "local_week", then the first day of the week is locale-
934 dependent. For example, in the "en-US" locale, the first day of the
935 week is Sunday.
936
937 $dt->set_locale($locale)
938
939 Sets the object's locale. You can provide either a locale code like
940 "en-US" or an object returned by "DateTime::Locale->load".
941
942 $dt->set_time_zone($tz)
943
944 This method accepts either a time zone object or a string that can be
945 passed as the "name" parameter to "DateTime::TimeZone->new". If the new
946 time zone's offset is different from the old time zone, then the local
947 time is adjusted accordingly.
948
949 For example:
950
951 my $dt = DateTime->new(
952 year => 2000,
953 month => 5,
954 day => 10,
955 hour => 15,
956 minute => 15,
957 time_zone => 'America/Los_Angeles',
958 );
959
960 print $dt->hour; # prints 15
961
962 $dt->set_time_zone('America/Chicago');
963
964 print $dt->hour; # prints 17
965
966 If the old time zone was a floating time zone, then no adjustments to
967 the local time are made, except to account for leap seconds. If the new
968 time zone is floating, then the UTC time is adjusted in order to leave
969 the local time untouched.
970
971 Fans of Tsai Ming-Liang's films will be happy to know that this does
972 work:
973
974 my $dt = DateTime->now( time_zone => 'Asia/Taipei' );
975 $dt->set_time_zone('Europe/Paris');
976
977 Yes, now we can know "ni3 na4 bian1 ji2 dian3?"
978
979 $dt->set_formatter($formatter)
980
981 Sets the formatter for the object. See "Formatters And Stringification"
982 for details.
983
984 You can set this to "undef" to revert to the default formatter.
985
986 Math Methods
987 Like the set methods, math related methods always return the object
988 itself, to allow for chaining:
989
990 $dt->add( days => 1 )->subtract( seconds => 1 );
991
992 $dt->duration_class
993
994 This returns "DateTime::Duration", but exists so that a subclass of
995 "DateTime" can provide a different value.
996
997 $dt->add_duration($duration_object)
998
999 This method adds a DateTime::Duration to the current datetime. See the
1000 DateTime::Duration docs for more details.
1001
1002 $dt->add( parameters for DateTime::Duration )
1003
1004 This method is syntactic sugar around the "$dt->add_duration" method.
1005 It simply creates a new DateTime::Duration object using the parameters
1006 given, and then calls the "$dt->add_duration" method.
1007
1008 $dt->add($duration_object)
1009
1010 A synonym of "$dt->add_duration($duration_object)".
1011
1012 $dt->subtract_duration($duration_object)
1013
1014 When given a DateTime::Duration object, this method simply calls
1015 "$dur->inverse" on that object and passes that new duration to the
1016 "$self->add_duration" method.
1017
1018 $dt->subtract( DateTime::Duration->new parameters )
1019
1020 Like "$dt->add", this is syntactic sugar for the
1021 "$dt->subtract_duration" method.
1022
1023 $dt->subtract($duration_object)
1024
1025 A synonym of "$dt->subtract_duration($duration_object)".
1026
1027 $dt->subtract_datetime($datetime)
1028
1029 This method returns a new DateTime::Duration object representing the
1030 difference between the two dates. The duration is relative to the
1031 object from which $datetime is subtracted. For example:
1032
1033 2003-03-15 00:00:00.00000000
1034 - 2003-02-15 00:00:00.00000000
1035 -------------------------------
1036 = 1 month
1037
1038 Note that this duration is not an absolute measure of the amount of
1039 time between the two datetimes, because the length of a month varies,
1040 as well as due to the presence of leap seconds.
1041
1042 The returned duration may have deltas for months, days, minutes,
1043 seconds, and nanoseconds.
1044
1045 $dt->delta_md($datetime)
1046
1047 $dt->delta_days($datetime)
1048
1049 Each of these methods returns a new DateTime::Duration object
1050 representing some portion of the difference between two datetimes. The
1051 "$dt->delta_md" method returns a duration which contains only the month
1052 and day portions of the duration is represented. The "$dt->delta_days"
1053 method returns a duration which contains only days.
1054
1055 The "$dt->delta_md" and "$dt->delta_days" methods truncate the duration
1056 so that any fractional portion of a day is ignored. Both of these
1057 methods operate on the date portion of a datetime only, and so
1058 effectively ignore the time zone.
1059
1060 Unlike the subtraction methods, these methods always return a positive
1061 (or zero) duration.
1062
1063 $dt->delta_ms($datetime)
1064
1065 Returns a duration which contains only minutes and seconds. Any day and
1066 month differences are converted to minutes and seconds. This method
1067 always returns a positive (or zero) duration.
1068
1069 $dt->subtract_datetime_absolute($datetime)
1070
1071 This method returns a new DateTime::Duration object representing the
1072 difference between the two dates in seconds and nanoseconds. This is
1073 the only way to accurately measure the absolute amount of time between
1074 two datetimes, since units larger than a second do not represent a
1075 fixed number of seconds.
1076
1077 Note that because of leap seconds, this may not return the same result
1078 as doing this math based on the value returned by "$dt->epoch".
1079
1080 $dt->is_between( $lower, $upper )
1081
1082 Checks whether $dt is strictly between two other DateTime objects.
1083
1084 "Strictly" means that $dt must be greater than $lower and less than
1085 $upper. If it is equal to either object then this method returns false.
1086
1087 Class Methods
1088 DateTime->DefaultLocale($locale)
1089
1090 This can be used to specify the default locale to be used when creating
1091 DateTime objects. If unset, then "en-US" is used.
1092
1093 This exists for backwards compatibility, but is probably best avoided.
1094 This will change the default locale for every "DateTime" object created
1095 in your application, even those created by third party libraries which
1096 also use "DateTime".
1097
1098 DateTime->compare( $dt1, $dt2 ), DateTime->compare_ignore_floating(
1099 $dt1, $dt2 )
1100
1101 $cmp = DateTime->compare( $dt1, $dt2 );
1102
1103 $cmp = DateTime->compare_ignore_floating( $dt1, $dt2 );
1104
1105 This method compare two DateTime objects. The semantics are compatible
1106 with Perl's "sort" function; it returns "-1" if "$dt1 < $dt2", 0 if
1107 "$dt1 == $dt2", 1 if "$dt1 > $dt2".
1108
1109 If one of the two DateTime objects has a floating time zone, it will
1110 first be converted to the time zone of the other object. This is what
1111 you want most of the time, but it can lead to inconsistent results when
1112 you compare a number of DateTime objects, some of which are floating,
1113 and some of which are in other time zones.
1114
1115 If you want to have consistent results (because you want to sort an
1116 array of objects, for example), you can use the
1117 "compare_ignore_floating" method:
1118
1119 @dates = sort { DateTime->compare_ignore_floating( $a, $b ) } @dates;
1120
1121 In this case, objects with a floating time zone will be sorted as if
1122 they were UTC times.
1123
1124 Since DateTime objects overload comparison operators, this:
1125
1126 @dates = sort @dates;
1127
1128 is equivalent to this:
1129
1130 @dates = sort { DateTime->compare( $a, $b ) } @dates;
1131
1132 DateTime objects can be compared to any other calendar class that
1133 implements the "utc_rd_values" method.
1134
1135 Testing Code That Uses DateTime
1136 If you are trying to test code that calls uses DateTime, you may want
1137 to be to explicitly set the value returned by Perl's "time" builtin.
1138 This builtin is called by "DateTime->now" and "DateTime->today".
1139
1140 You can override "CORE::GLOBAL::time", but this will only work if you
1141 do this before loading DateTime. If doing this is inconvenient, you can
1142 also override "DateTime::_core_time":
1143
1144 no warnings 'redefine';
1145 local *DateTime::_core_time = sub { return 42 };
1146
1147 DateTime is guaranteed to call this subroutine to get the current
1148 "time" value. You can also override the "_core_time" sub in a subclass
1149 of DateTime and use that.
1150
1151 How DateTime Math Works
1152 It's important to have some understanding of how datetime math is
1153 implemented in order to effectively use this module and
1154 DateTime::Duration.
1155
1156 Making Things Simple
1157
1158 If you want to simplify your life and not have to think too hard about
1159 the nitty-gritty of datetime math, I have several recommendations:
1160
1161 • use the floating time zone
1162
1163 If you do not care about time zones or leap seconds, use the
1164 "floating" timezone:
1165
1166 my $dt = DateTime->now( time_zone => 'floating' );
1167
1168 Math done on two objects in the floating time zone produces very
1169 predictable results.
1170
1171 Note that in most cases you will want to start by creating an
1172 object in a specific zone and then convert it to the floating time
1173 zone. When an object goes from a real zone to the floating zone,
1174 the time for the object remains the same.
1175
1176 This means that passing the floating zone to a constructor may not
1177 do what you want.
1178
1179 my $dt = DateTime->now( time_zone => 'floating' );
1180
1181 is equivalent to
1182
1183 my $dt = DateTime->now( time_zone => 'UTC' )->set_time_zone('floating');
1184
1185 This might not be what you wanted. Instead, you may prefer to do
1186 this:
1187
1188 my $dt = DateTime->now( time_zone => 'local' )->set_time_zone('floating');
1189
1190 • use UTC for all calculations
1191
1192 If you do care about time zones (particularly DST) or leap seconds,
1193 try to use non-UTC time zones for presentation and user input only.
1194 Convert to UTC immediately and convert back to the local time zone
1195 for presentation:
1196
1197 my $dt = DateTime->new( %user_input, time_zone => $user_tz );
1198 $dt->set_time_zone('UTC');
1199
1200 # do various operations - store it, retrieve it, add, subtract, etc.
1201
1202 $dt->set_time_zone($user_tz);
1203 print $dt->datetime;
1204
1205 • math on non-UTC time zones
1206
1207 If you need to do date math on objects with non-UTC time zones,
1208 please read the caveats below carefully. The results "DateTime"
1209 produces are predictable, correct, and mostly intuitive, but
1210 datetime math gets very ugly when time zones are involved, and
1211 there are a few strange corner cases involving subtraction of two
1212 datetimes across a DST change.
1213
1214 If you can always use the floating or UTC time zones, you can skip
1215 ahead to "Leap Seconds and Date Math"
1216
1217 • date vs datetime math
1218
1219 If you only care about the date (calendar) portion of a datetime,
1220 you should use either "$dt->delta_md"> or "$dt->delta_days", not
1221 "$dt->subtract_datetime". This will give predictable, unsurprising
1222 results, free from DST-related complications.
1223
1224 • $dt->subtract_datetime and $dt->add_duration
1225
1226 You must convert your datetime objects to the UTC time zone before
1227 doing date math if you want to make sure that the following
1228 formulas are always true:
1229
1230 $dt2 - $dt1 = $dur
1231 $dt1 + $dur = $dt2
1232 $dt2 - $dur = $dt1
1233
1234 Note that using "$dt->delta_days" ensures that this formula always
1235 works, regardless of the time zones of the objects involved, as
1236 does using "$dt->subtract_datetime_absolute". Other methods of
1237 subtraction are not always reversible.
1238
1239 • never do math on two objects where only one is in the floating time
1240 zone
1241
1242 The date math code accounts for leap seconds whenever the
1243 "DateTime" object is not in the floating time zone. If you try to
1244 do math where one object is in the floating zone and the other
1245 isn't, the results will be confusing and wrong.
1246
1247 Adding a Duration to a DateTime
1248
1249 The parts of a duration can be broken down into five parts. These are
1250 months, days, minutes, seconds, and nanoseconds. Adding one month to a
1251 date is different than adding 4 weeks or 28, 29, 30, or 31 days.
1252 Similarly, due to DST and leap seconds, adding a day can be different
1253 than adding 86,400 seconds, and adding a minute is not exactly the same
1254 as 60 seconds.
1255
1256 We cannot convert between these units, except for seconds and
1257 nanoseconds, because there is no fixed conversion between most pairs of
1258 units. That is because of things like leap seconds, DST changes, etc.
1259
1260 "DateTime" always adds (or subtracts) days, then months, minutes, and
1261 then seconds and nanoseconds. If there are any boundary overflows,
1262 these are normalized at each step. For the days and months the local
1263 (not UTC) values are used. For minutes and seconds, the local values
1264 are used. This generally just works.
1265
1266 This means that adding one month and one day to February 28, 2003 will
1267 produce the date April 1, 2003, not March 29, 2003.
1268
1269 my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
1270
1271 $dt->add( months => 1, days => 1 );
1272
1273 # 2003-04-01 - the result
1274
1275 On the other hand, if we add months first, and then separately add
1276 days, we end up with March 29, 2003:
1277
1278 $dt->add( months => 1 )->add( days => 1 );
1279
1280 # 2003-03-29
1281
1282 We see similar strangeness when math crosses a DST boundary:
1283
1284 my $dt = DateTime->new(
1285 year => 2003,
1286 month => 4,
1287 day => 5,
1288 hour => 1,
1289 minute => 58,
1290 time_zone => "America/Chicago",
1291 );
1292
1293 $dt->add( days => 1, minutes => 3 );
1294 # 2003-04-06 02:01:00
1295
1296 $dt->add( minutes => 3 )->add( days => 1 );
1297 # 2003-04-06 03:01:00
1298
1299 Note that if you converted the datetime object to UTC first you would
1300 get predictable results.
1301
1302 If you want to know how many seconds a DateTime::Duration object
1303 represents, you have to add it to a datetime to find out, so you could
1304 do:
1305
1306 my $now = DateTime->now( time_zone => 'UTC' );
1307 my $later = $now->clone->add_duration($duration);
1308
1309 my $seconds_dur = $later->subtract_datetime_absolute($now);
1310
1311 This returns a DateTime::Duration which only contains seconds and
1312 nanoseconds.
1313
1314 If we were add the duration to a different "DateTime" object we might
1315 get a different number of seconds.
1316
1317 DateTime::Duration supports three different end-of-month algorithms for
1318 adding months. This comes into play when an addition results in a day
1319 past the end of the following month (for example, adding one month to
1320 January 30).
1321
1322 # 2010-08-31 + 1 month = 2010-10-01
1323 $dt->add( months => 1, end_of_month => 'wrap' );
1324
1325 # 2010-01-30 + 1 month = 2010-02-28
1326 $dt->add( months => 1, end_of_month => 'limit' );
1327
1328 # 2010-04-30 + 1 month = 2010-05-31
1329 $dt->add( months => 1, end_of_month => 'preserve' );
1330
1331 By default, it uses "wrap" for positive durations and "preserve" for
1332 negative durations. See DateTime::Duration for a detailed explanation
1333 of these algorithms.
1334
1335 If you need to do lots of work with durations, take a look at the
1336 DateTime::Format::Duration module, which lets you present information
1337 from durations in many useful ways.
1338
1339 There are other subtract/delta methods in "DateTime" to generate
1340 different types of durations. These methods are
1341 "$dt->subtract_datetime", "$dt->subtract_datetime_absolute",
1342 "$dt->delta_md", "$dt->delta_days", and "$dt->delta_ms".
1343
1344 DateTime Subtraction
1345
1346 Date subtraction is done based solely on the two object's local
1347 datetimes, with one exception to handle DST changes. Also, if the two
1348 datetime objects are in different time zones, one of them is converted
1349 to the other's time zone first before subtraction. This is best
1350 explained through examples:
1351
1352 The first of these probably makes the most sense:
1353
1354 # not DST
1355 my $dt1 = DateTime->new(
1356 year => 2003,
1357 month => 5,
1358 day => 6,
1359 time_zone => 'America/Chicago',
1360 );
1361
1362 # is DST
1363 my $dt2 = DateTime->new(
1364 year => 2003,
1365 month => 11,
1366 day => 6,
1367 time_zone => 'America/Chicago',
1368 );
1369
1370 # 6 months
1371 my $dur = $dt2->subtract_datetime($dt1);
1372
1373 Nice and simple.
1374
1375 This one is a little trickier, but still fairly logical:
1376
1377 # is DST
1378 my $dt1 = DateTime->new(
1379 year => 2003,
1380 month => 4,
1381 day => 5,
1382 hour => 1,
1383 minute => 58,
1384 time_zone => "America/Chicago",
1385 );
1386
1387 # not DST
1388 my $dt2 = DateTime->new(
1389 year => 2003,
1390 month => 4,
1391 day => 7,
1392 hour => 2,
1393 minute => 1,
1394 time_zone => "America/Chicago",
1395 );
1396
1397 # 2 days and 3 minutes
1398 my $dur = $dt2->subtract_datetime($dt1);
1399
1400 Which contradicts the result this one gives, even though they both make
1401 sense:
1402
1403 # is DST
1404 my $dt1 = DateTime->new(
1405 year => 2003,
1406 month => 4,
1407 day => 5,
1408 hour => 1,
1409 minute => 58,
1410 time_zone => "America/Chicago",
1411 );
1412
1413 # not DST
1414 my $dt2 = DateTime->new(
1415 year => 2003,
1416 month => 4,
1417 day => 6,
1418 hour => 3,
1419 minute => 1,
1420 time_zone => "America/Chicago",
1421 );
1422
1423 # 1 day and 3 minutes
1424 my $dur = $dt2->subtract_datetime($dt1);
1425
1426 This last example illustrates the "DST" exception mentioned earlier.
1427 The exception accounts for the fact 2003-04-06 only lasts 23 hours.
1428
1429 And finally:
1430
1431 my $dt2 = DateTime->new(
1432 year => 2003,
1433 month => 10,
1434 day => 26,
1435 hour => 1,
1436 time_zone => 'America/Chicago',
1437 );
1438
1439 my $dt1 = $dt2->clone->subtract( hours => 1 );
1440
1441 # 60 minutes
1442 my $dur = $dt2->subtract_datetime($dt1);
1443
1444 This seems obvious until you realize that subtracting 60 minutes from
1445 $dt2 in the above example still leaves the clock time at "01:00:00".
1446 This time we are accounting for a 25 hour day.
1447
1448 Reversibility
1449
1450 Date math operations are not always reversible. This is because of the
1451 way that addition operations are ordered. As was discussed earlier,
1452 adding 1 day and 3 minutes in one call to "$dt->add"> is not the same
1453 as first adding 3 minutes and 1 day in two separate calls.
1454
1455 If we take a duration returned from "$dt->subtract_datetime" and then
1456 try to add or subtract that duration from one of the datetimes we just
1457 used, we sometimes get interesting results:
1458
1459 my $dt1 = DateTime->new(
1460 year => 2003,
1461 month => 4,
1462 day => 5,
1463 hour => 1,
1464 minute => 58,
1465 time_zone => "America/Chicago",
1466 );
1467
1468 my $dt2 = DateTime->new(
1469 year => 2003,
1470 month => 4,
1471 day => 6,
1472 hour => 3,
1473 minute => 1,
1474 time_zone => "America/Chicago",
1475 );
1476
1477 # 1 day and 3 minutes
1478 my $dur = $dt2->subtract_datetime($dt1);
1479
1480 # gives us $dt2
1481 $dt1->add_duration($dur);
1482
1483 # gives us 2003-04-05 02:58:00 - 1 hour later than $dt1
1484 $dt2->subtract_duration($dur);
1485
1486 The "$dt->subtract_duration" operation gives us a (perhaps) unexpected
1487 answer because it first subtracts one day to get 2003-04-05T03:01:00
1488 and then subtracts 3 minutes to get the final result.
1489
1490 If we explicitly reverse the order we can get the original value of
1491 $dt1. This can be facilitated by the DateTime::Duration class's
1492 "$dur->calendar_duration" and "$dur->clock_duration" methods:
1493
1494 $dt2->subtract_duration( $dur->clock_duration )
1495 ->subtract_duration( $dur->calendar_duration );
1496
1497 Leap Seconds and Date Math
1498
1499 The presence of leap seconds can cause even more anomalies in date
1500 math. For example, the following is a legal datetime:
1501
1502 my $dt = DateTime->new(
1503 year => 1972,
1504 month => 12,
1505 day => 31,
1506 hour => 23,
1507 minute => 59,
1508 second => 60,
1509 time_zone => 'UTC'
1510 );
1511
1512 If we add one month ...
1513
1514 $dt->add( months => 1 );
1515
1516 ... the datetime is now "1973-02-01 00:00:00", because there is no
1517 23:59:60 on 1973-01-31.
1518
1519 Leap seconds also force us to distinguish between minutes and seconds
1520 during date math. Given the following datetime ...
1521
1522 my $dt = DateTime->new(
1523 year => 1972,
1524 month => 12,
1525 day => 31,
1526 hour => 23,
1527 minute => 59,
1528 second => 30,
1529 time_zone => 'UTC'
1530 );
1531
1532 ... we will get different results when adding 1 minute than we get if
1533 we add 60 seconds. This is because in this case, the last minute of the
1534 day, beginning at 23:59:00, actually contains 61 seconds.
1535
1536 Here are the results we get:
1537
1538 # 1972-12-31 23:59:30 - our starting datetime
1539 my $dt = DateTime->new(
1540 year => 1972,
1541 month => 12,
1542 day => 31,
1543 hour => 23,
1544 minute => 59,
1545 second => 30,
1546 time_zone => 'UTC'
1547 );
1548
1549 # 1973-01-01 00:00:30 - one minute later
1550 $dt->clone->add( minutes => 1 );
1551
1552 # 1973-01-01 00:00:29 - 60 seconds later
1553 $dt->clone->add( seconds => 60 );
1554
1555 # 1973-01-01 00:00:30 - 61 seconds later
1556 $dt->clone->add( seconds => 61 );
1557
1558 Local vs. UTC and 24 hours vs. 1 day
1559
1560 When math crosses a daylight saving boundary, a single day may have
1561 more or less than 24 hours.
1562
1563 For example, if you do this ...
1564
1565 my $dt = DateTime->new(
1566 year => 2003,
1567 month => 4,
1568 day => 5,
1569 hour => 2,
1570 time_zone => 'America/Chicago',
1571 );
1572
1573 $dt->add( days => 1 );
1574
1575 ... then you will produce an invalid local time, and therefore an
1576 exception will be thrown.
1577
1578 However, this works ...
1579
1580 my $dt = DateTime->new(
1581 year => 2003,
1582 month => 4,
1583 day => 5,
1584 hour => 2,
1585 time_zone => 'America/Chicago',
1586 );
1587
1588 $dt->add( hours => 24 );
1589
1590 ... and produces a datetime with the local time of "03:00".
1591
1592 If all this makes your head hurt, there is a simple alternative. Just
1593 convert your datetime object to the "UTC" time zone before doing date
1594 math on it, and switch it back to the local time zone afterwards. This
1595 avoids the possibility of having date math throw an exception, and
1596 makes sure that 1 day equals 24 hours. Of course, this may not always
1597 be desirable, so caveat user!
1598
1599 Overloading
1600 This module explicitly overloads the addition (+), subtraction (-),
1601 string and numeric comparison operators. This means that the following
1602 all do sensible things:
1603
1604 my $new_dt = $dt + $duration_obj;
1605
1606 my $new_dt = $dt - $duration_obj;
1607
1608 my $duration_obj = $dt - $new_dt;
1609
1610 foreach my $dt ( sort @dts ) {...}
1611
1612 Additionally, the fallback parameter is set to true, so other derivable
1613 operators (+=, -=, etc.) will work properly. Do not expect increment
1614 (++) or decrement (--) to do anything useful.
1615
1616 The string comparison operators, "eq" or "ne", will use the string
1617 value to compare with non-DateTime objects.
1618
1619 DateTime objects do not have a numeric value, using "==" or "<=>" to
1620 compare a DateTime object with a non-DateTime object will result in an
1621 exception. To safely sort mixed DateTime and non-DateTime objects, use
1622 "sort { $a cmp $b } @dates".
1623
1624 The module also overloads stringification using the object's formatter,
1625 defaulting to "iso8601" method. See "Formatters And Stringification"
1626 for details.
1627
1628 Formatters And Stringification
1629 You can optionally specify a "formatter", which is usually a
1630 "DateTime::Format::*" object or class, to control the stringification
1631 of the DateTime object.
1632
1633 Any of the constructor methods can accept a formatter argument:
1634
1635 my $formatter = DateTime::Format::Strptime->new(...);
1636 my $dt = DateTime->new( year => 2004, formatter => $formatter );
1637
1638 Or, you can set it afterwards:
1639
1640 $dt->set_formatter($formatter);
1641 $formatter = $dt->formatter;
1642
1643 Once you set the formatter, the overloaded stringification method will
1644 use the formatter. If unspecified, the "iso8601" method is used.
1645
1646 A formatter can be handy when you know that in your application you
1647 want to stringify your DateTime objects into a special format all the
1648 time, for example in Postgres format.
1649
1650 If you provide a formatter class name or object, it must implement a
1651 "format_datetime" method. This method will be called with just the
1652 "DateTime" object as its argument.
1653
1654 CLDR Patterns
1655 The CLDR pattern language is both more powerful and more complex than
1656 strftime. Unlike strftime patterns, you often have to explicitly escape
1657 text that you do not want formatted, as the patterns are simply letters
1658 without any prefix.
1659
1660 For example, "yyyy-MM-dd" is a valid CLDR pattern. If you want to
1661 include any lower or upper case ASCII characters as-is, you can
1662 surround them with single quotes ('). If you want to include a single
1663 quote, you must escape it as two single quotes ('').
1664
1665 my $pattern1 = q{'Today is ' EEEE};
1666 my $pattern2 = q{'It is now' h 'o''clock' a};
1667
1668 Spaces and any non-letter text will always be passed through as-is.
1669
1670 Many CLDR patterns which produce numbers will pad the number with
1671 leading zeroes depending on the length of the format specifier. For
1672 example, "h" represents the current hour from 1-12. If you specify "hh"
1673 then hours 1-9 will have a leading zero prepended.
1674
1675 However, CLDR often uses five of a letter to represent the narrow form
1676 of a pattern. This inconsistency is necessary for backwards
1677 compatibility.
1678
1679 There are many cases where CLDR patterns distinguish between the
1680 "format" and "stand-alone" forms of a pattern. The format pattern is
1681 used when the thing in question is being placed into a larger string.
1682 The stand-alone form is used when displaying that item by itself, for
1683 example in a calendar.
1684
1685 There are also many cases where CLDR provides three sizes for each
1686 item, wide (the full name), abbreviated, and narrow. The narrow form is
1687 often just a single character, for example "T" for "Tuesday", and may
1688 not be unique.
1689
1690 CLDR provides a fairly complex system for localizing time zones that we
1691 ignore entirely. The time zone patterns just use the information
1692 provided by "DateTime::TimeZone", and do not follow the CLDR spec.
1693
1694 The output of a CLDR pattern is always localized, when applicable.
1695
1696 CLDR provides the following patterns:
1697
1698 • G{1,3}
1699
1700 The abbreviated era (BC, AD).
1701
1702 • GGGG
1703
1704 The wide era (Before Christ, Anno Domini).
1705
1706 • GGGGG
1707
1708 The narrow era, if it exists (but it mostly doesn't).
1709
1710 • y and y{3,}
1711
1712 The year, zero-prefixed as needed. Negative years will start with a
1713 "-", and this will be included in the length calculation.
1714
1715 In other, words the "yyyyy" pattern will format year -1234 as
1716 "-1234", not "-01234".
1717
1718 • yy
1719
1720 This is a special case. It always produces a two-digit year, so
1721 "1976" becomes "76". Negative years will start with a "-", making
1722 them one character longer.
1723
1724 • Y{1,}
1725
1726 The year in "week of the year" calendars, from "$dt->week_year".
1727
1728 • u{1,}
1729
1730 Same as "y" except that "uu" is not a special case.
1731
1732 • Q{1,2}
1733
1734 The quarter as a number (1..4).
1735
1736 • QQQ
1737
1738 The abbreviated format form for the quarter.
1739
1740 • QQQQ
1741
1742 The wide format form for the quarter.
1743
1744 • q{1,2}
1745
1746 The quarter as a number (1..4).
1747
1748 • qqq
1749
1750 The abbreviated stand-alone form for the quarter.
1751
1752 • qqqq
1753
1754 The wide stand-alone form for the quarter.
1755
1756 • M{1,2]
1757
1758 The numerical month.
1759
1760 • MMM
1761
1762 The abbreviated format form for the month.
1763
1764 • MMMM
1765
1766 The wide format form for the month.
1767
1768 • MMMMM
1769
1770 The narrow format form for the month.
1771
1772 • L{1,2]
1773
1774 The numerical month.
1775
1776 • LLL
1777
1778 The abbreviated stand-alone form for the month.
1779
1780 • LLLL
1781
1782 The wide stand-alone form for the month.
1783
1784 • LLLLL
1785
1786 The narrow stand-alone form for the month.
1787
1788 • w{1,2}
1789
1790 The week of the year, from "$dt->week_number".
1791
1792 • W
1793
1794 The week of the month, from "$dt->week_of_month".
1795
1796 • d{1,2}
1797
1798 The numeric day of the month.
1799
1800 • D{1,3}
1801
1802 The numeric day of the year.
1803
1804 • F
1805
1806 The day of the week in the month, from "$dt->weekday_of_month".
1807
1808 • g{1,}
1809
1810 The modified Julian day, from "$dt->mjd".
1811
1812 • E{1,3} and eee
1813
1814 The abbreviated format form for the day of the week.
1815
1816 • EEEE and eeee
1817
1818 The wide format form for the day of the week.
1819
1820 • EEEEE and eeeee
1821
1822 The narrow format form for the day of the week.
1823
1824 • e{1,2}
1825
1826 The local numeric day of the week, from 1 to 7. This number depends
1827 on what day is considered the first day of the week, which varies
1828 by locale. For example, in the US, Sunday is the first day of the
1829 week, so this returns 2 for Monday.
1830
1831 • c
1832
1833 The numeric day of the week from 1 to 7, treating Monday as the
1834 first of the week, regardless of locale.
1835
1836 • ccc
1837
1838 The abbreviated stand-alone form for the day of the week.
1839
1840 • cccc
1841
1842 The wide stand-alone form for the day of the week.
1843
1844 • ccccc
1845
1846 The narrow format form for the day of the week.
1847
1848 • a
1849
1850 The localized form of AM or PM for the time.
1851
1852 • h{1,2}
1853
1854 The hour from 1-12.
1855
1856 • H{1,2}
1857
1858 The hour from 0-23.
1859
1860 • K{1,2}
1861
1862 The hour from 0-11.
1863
1864 • k{1,2}
1865
1866 The hour from 1-24.
1867
1868 • j{1,2}
1869
1870 The hour, in 12 or 24 hour form, based on the preferred form for
1871 the locale. In other words, this is equivalent to either "h{1,2}"
1872 or "H{1,2}".
1873
1874 • m{1,2}
1875
1876 The minute.
1877
1878 • s{1,2}
1879
1880 The second.
1881
1882 • S{1,}
1883
1884 The fractional portion of the seconds, rounded based on the length
1885 of the specifier. This returned without a leading decimal point,
1886 but may have leading or trailing zeroes.
1887
1888 • A{1,}
1889
1890 The millisecond of the day, based on the current time. In other
1891 words, if it is 12:00:00.00, this returns 43200000.
1892
1893 • z{1,3}
1894
1895 The time zone short name.
1896
1897 • zzzz
1898
1899 The time zone long name.
1900
1901 • Z{1,3}
1902
1903 The time zone offset.
1904
1905 • ZZZZ
1906
1907 The time zone short name and the offset as one string, so something
1908 like "CDT-0500".
1909
1910 • ZZZZZ
1911
1912 The time zone offset as a sexagesimal number, so something like
1913 "-05:00". (This is useful for W3C format.)
1914
1915 • v{1,3}
1916
1917 The time zone short name.
1918
1919 • vvvv
1920
1921 The time zone long name.
1922
1923 • V{1,3}
1924
1925 The time zone short name.
1926
1927 • VVVV
1928
1929 The time zone long name.
1930
1931 CLDR "Available Formats"
1932
1933 The CLDR data includes pre-defined formats for various patterns such as
1934 "month and day" or "time of day". Using these formats lets you render
1935 information about a datetime in the most natural way for users from a
1936 given locale.
1937
1938 These formats are indexed by a key that is itself a CLDR pattern. When
1939 you look these up, you get back a different CLDR pattern suitable for
1940 the locale.
1941
1942 Let's look at some example We'll use "2008-02-05T18:30:30" as our
1943 example datetime value, and see how this is rendered for the "en-US"
1944 and "fr-FR" locales.
1945
1946 • "MMMd"
1947
1948 The abbreviated month and day as number. For "en-US", we get the
1949 pattern "MMM d", which renders as "Feb 5". For "fr-FR", we get the
1950 pattern "d MMM", which renders as "5 févr.".
1951
1952 • "yQQQ"
1953
1954 The year and abbreviated quarter of year. For "en-US", we get the
1955 pattern "QQQ y", which renders as "Q1 2008". For "fr-FR", we get
1956 the same pattern, "QQQ y", which renders as "T1 2008".
1957
1958 • "hm"
1959
1960 The 12-hour time of day without seconds. For "en-US", we get the
1961 pattern "h:mm a", which renders as "6:30 PM". For "fr-FR", we get
1962 the exact same pattern and rendering.
1963
1964 The available formats for each locale are documented in the POD for
1965 that locale. To get back the format, you use the "$locale->format_for"
1966 method. For example:
1967
1968 say $dt->format_cldr( $dt->locale->format_for('MMMd') );
1969
1970 strftime Patterns
1971 The following patterns are allowed in the format string given to the
1972 "$dt->strftime" method:
1973
1974 • %a
1975
1976 The abbreviated weekday name.
1977
1978 • %A
1979
1980 The full weekday name.
1981
1982 • %b
1983
1984 The abbreviated month name.
1985
1986 • %B
1987
1988 The full month name.
1989
1990 • %c
1991
1992 The default datetime format for the object's locale.
1993
1994 • %C
1995
1996 The century number (year/100) as a 2-digit integer.
1997
1998 • %d
1999
2000 The day of the month as a decimal number (range 01 to 31).
2001
2002 • %D
2003
2004 Equivalent to %m/%d/%y. This is not a good standard format if you
2005 want folks from both the United States and the rest of the world to
2006 understand the date!
2007
2008 • %e
2009
2010 Like %d, the day of the month as a decimal number, but a leading
2011 zero is replaced by a space.
2012
2013 • %F
2014
2015 Equivalent to %Y-%m-%d (the ISO 8601 date format)
2016
2017 • %G
2018
2019 The ISO 8601 year with century as a decimal number. The 4-digit
2020 year corresponding to the ISO week number (see %V). This has the
2021 same format and value as %Y, except that if the ISO week number
2022 belongs to the previous or next year, that year is used instead.
2023 (TZ)
2024
2025 • %g
2026
2027 Like %G, but without century, i.e., with a 2-digit year (00-99).
2028
2029 • %h
2030
2031 Equivalent to %b.
2032
2033 • %H
2034
2035 The hour as a decimal number using a 24-hour clock (range 00 to
2036 23).
2037
2038 • %I
2039
2040 The hour as a decimal number using a 12-hour clock (range 01 to
2041 12).
2042
2043 • %j
2044
2045 The day of the year as a decimal number (range 001 to 366).
2046
2047 • %k
2048
2049 The hour (24-hour clock) as a decimal number (range 0 to 23);
2050 single digits are preceded by a blank. (See also %H.)
2051
2052 • %l
2053
2054 The hour (12-hour clock) as a decimal number (range 1 to 12);
2055 single digits are preceded by a blank. (See also %I.)
2056
2057 • %m
2058
2059 The month as a decimal number (range 01 to 12).
2060
2061 • %M
2062
2063 The minute as a decimal number (range 00 to 59).
2064
2065 • %n
2066
2067 A newline character.
2068
2069 • %N
2070
2071 The fractional seconds digits. Default is 9 digits (nanoseconds).
2072
2073 %3N milliseconds (3 digits)
2074 %6N microseconds (6 digits)
2075 %9N nanoseconds (9 digits)
2076
2077 This value will always be rounded down to the nearest integer.
2078
2079 • %p
2080
2081 Either `AM' or `PM' according to the given time value, or the
2082 corresponding strings for the current locale. Noon is treated as
2083 `pm' and midnight as `am'.
2084
2085 • %P
2086
2087 Like %p but in lowercase: `am' or `pm' or a corresponding string
2088 for the current locale.
2089
2090 • %r
2091
2092 The time in a.m. or p.m. notation. In the POSIX locale this is
2093 equivalent to `%I:%M:%S %p'.
2094
2095 • %R
2096
2097 The time in 24-hour notation (%H:%M). (SU) For a version including
2098 the seconds, see %T below.
2099
2100 • %s
2101
2102 The number of seconds since the epoch.
2103
2104 • %S
2105
2106 The second as a decimal number (range 00 to 61).
2107
2108 • %t
2109
2110 A tab character.
2111
2112 • %T
2113
2114 The time in 24-hour notation (%H:%M:%S).
2115
2116 • %u
2117
2118 The day of the week as a decimal, range 1 to 7, Monday being 1. See
2119 also %w.
2120
2121 • %U
2122
2123 The week number of the current year as a decimal number, range 00
2124 to 53, starting with the first Sunday as the first day of week 01.
2125 See also %V and %W.
2126
2127 • %V
2128
2129 The ISO 8601:1988 week number of the current year as a decimal
2130 number, range 01 to 53, where week 1 is the first week that has at
2131 least 4 days in the current year, and with Monday as the first day
2132 of the week. See also %U and %W.
2133
2134 • %w
2135
2136 The day of the week as a decimal, range 0 to 6, Sunday being 0. See
2137 also %u.
2138
2139 • %W
2140
2141 The week number of the current year as a decimal number, range 00
2142 to 53, starting with the first Monday as the first day of week 01.
2143
2144 • %x
2145
2146 The default date format for the object's locale.
2147
2148 • %X
2149
2150 The default time format for the object's locale.
2151
2152 • %y
2153
2154 The year as a decimal number without a century (range 00 to 99).
2155
2156 • %Y
2157
2158 The year as a decimal number including the century.
2159
2160 • %z
2161
2162 The time-zone as hour offset from UTC. Required to emit
2163 RFC822-conformant dates (using "%a, %d %b %Y %H:%M:%S %z").
2164
2165 • %Z
2166
2167 The short name for the time zone, typically an abbreviation like
2168 "EST" or "AEST".
2169
2170 • %%
2171
2172 A literal `%' character.
2173
2174 • %{method}
2175
2176 Any method name may be specified using the format "%{method}" name
2177 where "method" is a valid "DateTime" object method.
2178
2179 DateTime and Storable
2180 "DateTime" implements Storable hooks in order to reduce the size of a
2181 serialized "DateTime" object.
2182
2184 This module is part of a larger ecosystem of modules in the DateTime
2185 family.
2186
2187 DateTime::Set
2188 The DateTime::Set module represents sets (including recurrences) of
2189 datetimes. Many modules return sets or recurrences.
2190
2191 Format Modules
2192 The various format modules exist to parse and format datetimes. For
2193 example, DateTime::Format::HTTP parses dates according to the RFC 1123
2194 format:
2195
2196 my $datetime
2197 = DateTime::Format::HTTP->parse_datetime(
2198 'Thu Feb 3 17:03:55 GMT 1994');
2199
2200 print DateTime::Format::HTTP->format_datetime($datetime);
2201
2202 Most format modules are suitable for use as a "formatter" with a
2203 DateTime object.
2204
2205 All format modules start with DateTime::Format::
2206 <https://metacpan.org/search?q=datetime%3A%3Aformat>.
2207
2208 Calendar Modules
2209 There are a number of modules on CPAN that implement non-Gregorian
2210 calendars, such as the Chinese, Mayan, and Julian calendars.
2211
2212 All calendar modules start with DateTime::Calendar::
2213 <https://metacpan.org/search?q=datetime%3A%3Acalendar>.
2214
2215 Event Modules
2216 There are a number of modules that calculate the dates for events, such
2217 as Easter, Sunrise, etc.
2218
2219 All event modules start with DateTime::Event::
2220 <https://metacpan.org/search?q=datetime%3A%3Aevent>.
2221
2222 Others
2223 There are many other modules that work with DateTime, including modules
2224 in the DateTimeX namespace <https://metacpan.org/search?q=datetimex>
2225 namespace, as well as others.
2226
2227 See MetaCPAN <https://metacpan.org/search?q=datetime> for more modules.
2228
2230 The tests in 20infinite.t seem to fail on some machines, particularly
2231 on Win32. This appears to be related to Perl's internal handling of
2232 IEEE infinity and NaN, and seems to be highly platform/compiler/phase
2233 of moon dependent.
2234
2235 If you don't plan to use infinite datetimes you can probably ignore
2236 this. This will be fixed (perhaps) in future versions.
2237
2239 A Date with Perl <http://www.houseabsolute.com/presentations/a-date-
2240 with-perl/> - a talk I've given at a few YAPCs.
2241
2242 datetime@perl.org mailing list
2243 <http://lists.perl.org/list/datetime.html>
2244
2245 <http://datetime.perl.org/>
2246
2248 Bugs may be submitted at
2249 <https://github.com/houseabsolute/DateTime.pm/issues>.
2250
2251 There is a mailing list available for users of this distribution,
2252 <mailto:datetime@perl.org>.
2253
2254 I am also usually active on IRC as 'autarch' on "irc://irc.perl.org".
2255
2257 The source code repository for DateTime can be found at
2258 <https://github.com/houseabsolute/DateTime.pm>.
2259
2261 If you'd like to thank me for the work I've done on this module, please
2262 consider making a "donation" to me via PayPal. I spend a lot of free
2263 time creating free software, and would appreciate any support you'd
2264 care to offer.
2265
2266 Please note that I am not suggesting that you must do this in order for
2267 me to continue working on this particular software. I will continue to
2268 do so, inasmuch as I have in the past, for as long as it interests me.
2269
2270 Similarly, a donation made in this way will probably not make me work
2271 on this software much more, unless I get so many donations that I can
2272 consider working on free software full time (let's all have a chuckle
2273 at that together).
2274
2275 To donate, log into PayPal and send money to autarch@urth.org, or use
2276 the button at <https://www.urth.org/fs-donation.html>.
2277
2279 Dave Rolsky <autarch@urth.org>
2280
2282 • Ben Bennett <fiji@limey.net>
2283
2284 • Christian Hansen <chansen@cpan.org>
2285
2286 • Daisuke Maki <dmaki@cpan.org>
2287
2288 • Dan Book <grinnz@gmail.com>
2289
2290 • Dan Stewart <danielandrewstewart@gmail.com>
2291
2292 • David E. Wheeler <david@justatheory.com>
2293
2294 • David Precious <davidp@preshweb.co.uk>
2295
2296 • Doug Bell <madcityzen@gmail.com>
2297
2298 • Flávio Soibelmann Glock <fglock@gmail.com>
2299
2300 • Gianni Ceccarelli <gianni.ceccarelli@broadbean.com>
2301
2302 • Gregory Oschwald <oschwald@gmail.com>
2303
2304 • Hauke D <haukex@zero-g.net>
2305
2306 • Iain Truskett <deceased>
2307
2308 • Jason McIntosh <jmac@jmac.org>
2309
2310 • Joshua Hoblitt <jhoblitt@cpan.org>
2311
2312 • Karen Etheridge <ether@cpan.org>
2313
2314 • Mark Overmeer <mark@overmeer.net>
2315
2316 • Michael Conrad <mike@nrdvana.net>
2317
2318 • Michael R. Davis <mrdvt92@users.noreply.github.com>
2319
2320 • Mohammad S Anwar <mohammad.anwar@yahoo.com>
2321
2322 • M Somerville <dracos@users.noreply.github.com>
2323
2324 • Nick Tonkin <1nickt@users.noreply.github.com>
2325
2326 • Olaf Alders <olaf@wundersolutions.com>
2327
2328 • Ovid <curtis_ovid_poe@yahoo.com>
2329
2330 • Paul Howarth <paul@city-fan.org>
2331
2332 • Philippe Bruhat (BooK) <book@cpan.org>
2333
2334 • philip r brenan <philiprbrenan@gmail.com>
2335
2336 • Ricardo Signes <rjbs@cpan.org>
2337
2338 • Richard Bowen <bowen@cpan.org>
2339
2340 • Ron Hill <rkhill@cpan.org>
2341
2342 • Sam Kington <github@illuminated.co.uk>
2343
2344 • viviparous <viviparous@prc>
2345
2347 This software is Copyright (c) 2003 - 2020 by Dave Rolsky.
2348
2349 This is free software, licensed under:
2350
2351 The Artistic License 2.0 (GPL Compatible)
2352
2353 The full text of the license can be found in the LICENSE file included
2354 with this distribution.
2355
2356
2357
2358perl v5.32.1 2021-01-27 DateTime(3)