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