1DateTime(3) User Contributed Perl Documentation DateTime(3)
2
3
4
6 DateTime - A date and time object for Perl
7
9 version 1.51
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 Return 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.
779
780 Since the epoch does not account for leap seconds, the epoch time for
781 1972-12-31T23:59:60 (UTC) is exactly the same as that for
782 1973-01-01T00:00:00.
783
784 $dt->hires_epoch()
785
786 Returns the epoch as a floating point number. The floating point
787 portion of the value represents the nanosecond value of the object.
788 This method is provided for compatibility with the "Time::HiRes"
789 module.
790
791 Note that this method suffers from the imprecision of floating point
792 numbers, and the result may end up rounded to an arbitrary degree
793 depending on your platform.
794
795 my $dt = DateTime->new( year => 2012, nanosecond => 4 );
796 say $dt->hires_epoch();
797
798 On my system, this simply prints 1325376000 because adding 0.000000004
799 to 1325376000 returns 1325376000.
800
801 $dt->is_finite(), $dt->is_infinite()
802
803 These methods allow you to distinguish normal datetime objects from
804 infinite ones. Infinite datetime objects are documented in
805 DateTime::Infinite.
806
807 $dt->utc_rd_values()
808
809 Returns the current UTC Rata Die days, seconds, and nanoseconds as a
810 three element list. This exists primarily to allow other calendar
811 modules to create objects based on the values provided by this object.
812
813 $dt->local_rd_values()
814
815 Returns the current local Rata Die days, seconds, and nanoseconds as a
816 three element list. This exists for the benefit of other modules which
817 might want to use this information for date math, such as
818 "DateTime::Event::Recurrence".
819
820 $dt->leap_seconds()
821
822 Returns the number of leap seconds that have happened up to the
823 datetime represented by the object. For floating datetimes, this always
824 returns 0.
825
826 $dt->utc_rd_as_seconds()
827
828 Returns the current UTC Rata Die days and seconds purely as seconds.
829 This number ignores any fractional seconds stored in the object, as
830 well as leap seconds.
831
832 $dt->locale()
833
834 Returns the current locale object.
835
836 $dt->formatter()
837
838 Returns current formatter object or class. See "Formatters And
839 Stringification" for details.
840
841 "Set" Methods
842 The remaining methods provided by "DateTime.pm", except where otherwise
843 specified, return the object itself, thus making method chaining
844 possible. For example:
845
846 my $dt = DateTime->now->set_time_zone( 'Australia/Sydney' );
847
848 my $first = DateTime
849 ->last_day_of_month( year => 2003, month => 3 )
850 ->add( days => 1 )
851 ->subtract( seconds => 1 );
852
853 $dt->set( .. )
854
855 This method can be used to change the local components of a date time.
856 This method accepts any parameter allowed by the "new()" method except
857 for "locale" or "time_zone". Use "set_locale()" and "set_time_zone()"
858 for those instead.
859
860 This method performs parameter validation just like the "new()" method.
861
862 Do not use this method to do date math. Use the "add()" and
863 "subtract()" methods instead.
864
865 $dt->set_year(), $dt->set_month(), etc.
866
867 DateTime has a "set_*" method for every item that can be passed to the
868 constructor:
869
870 · $dt->set_year()
871
872 · $dt->set_month()
873
874 · $dt->set_day()
875
876 · $dt->set_hour()
877
878 · $dt->set_minute()
879
880 · $dt->set_second()
881
882 · $dt->set_nanosecond()
883
884 These are shortcuts to calling "set()" with a single key. They all take
885 a single parameter.
886
887 $dt->truncate( to => ... )
888
889 This method allows you to reset some of the local time components in
890 the object to their "zero" values. The "to" parameter is used to
891 specify which values to truncate, and it may be one of "year",
892 "quarter", "month", "week", "local_week", "day", "hour", "minute", or
893 "second".
894
895 For example, if "month" is specified, then the local day becomes 1, and
896 the hour, minute, and second all become 0.
897
898 If "week" is given, then the datetime is set to the Monday of the week
899 in which it occurs, and the time components are all set to 0. If you
900 truncate to "local_week", then the first day of the week is locale-
901 dependent. For example, in the "en-US" locale, the first day of the
902 week is Sunday.
903
904 $dt->set_locale( $locale )
905
906 Sets the object's locale. You can provide either a locale code like
907 "en-US" or an object returned by "DateTime::Locale->load".
908
909 $dt->set_time_zone( $tz )
910
911 This method accepts either a time zone object or a string that can be
912 passed as the "name" parameter to "DateTime::TimeZone->new()". If the
913 new time zone's offset is different from the old time zone, then the
914 local time is adjusted accordingly.
915
916 For example:
917
918 my $dt = DateTime->new(
919 year => 2000,
920 month => 5,
921 day => 10,
922 hour => 15,
923 minute => 15,
924 time_zone => 'America/Los_Angeles',
925 );
926
927 print $dt->hour; # prints 15
928
929 $dt->set_time_zone( 'America/Chicago' );
930
931 print $dt->hour; # prints 17
932
933 If the old time zone was a floating time zone, then no adjustments to
934 the local time are made, except to account for leap seconds. If the new
935 time zone is floating, then the UTC time is adjusted in order to leave
936 the local time untouched.
937
938 Fans of Tsai Ming-Liang's films will be happy to know that this does
939 work:
940
941 my $dt = DateTime->now( time_zone => 'Asia/Taipei' );
942
943 $dt->set_time_zone( 'Europe/Paris' );
944
945 Yes, now we can know "ni3 na4 bian1 ji2dian3?"
946
947 $dt->set_formatter( $formatter )
948
949 Set the formatter for the object. See "Formatters And Stringification"
950 for details.
951
952 You can set this to "undef" to revert to the default formatter.
953
954 Math Methods
955 Like the set methods, math related methods always return the object
956 itself, to allow for chaining:
957
958 $dt->add( days => 1 )->subtract( seconds => 1 );
959
960 $dt->duration_class()
961
962 This returns "DateTime::Duration", but exists so that a subclass of
963 "DateTime.pm" can provide a different value.
964
965 $dt->add_duration( $duration_object )
966
967 This method adds a "DateTime::Duration" to the current datetime. See
968 the DateTime::Duration docs for more details.
969
970 $dt->add( parameters for DateTime::Duration )
971
972 This method is syntactic sugar around the "add_duration()" method. It
973 simply creates a new "DateTime::Duration" object using the parameters
974 given, and then calls the "add_duration()" method.
975
976 $dt->add( $duration_object )
977
978 A synonym of "$dt->add_duration( $duration_object )".
979
980 $dt->subtract_duration( $duration_object )
981
982 When given a "DateTime::Duration" object, this method simply calls
983 "invert()" on that object and passes that new duration to the
984 "add_duration" method.
985
986 $dt->subtract( DateTime::Duration->new parameters )
987
988 Like "add()", this is syntactic sugar for the "subtract_duration()"
989 method.
990
991 $dt->subtract( $duration_object )
992
993 A synonym of "$dt->subtract_duration( $duration_object )".
994
995 $dt->subtract_datetime( $datetime )
996
997 This method returns a new "DateTime::Duration" object representing the
998 difference between the two dates. The duration is relative to the
999 object from which $datetime is subtracted. For example:
1000
1001 2003-03-15 00:00:00.00000000
1002 - 2003-02-15 00:00:00.00000000
1003 -------------------------------
1004 = 1 month
1005
1006 Note that this duration is not an absolute measure of the amount of
1007 time between the two datetimes, because the length of a month varies,
1008 as well as due to the presence of leap seconds.
1009
1010 The returned duration may have deltas for months, days, minutes,
1011 seconds, and nanoseconds.
1012
1013 $dt->delta_md( $datetime )
1014
1015 $dt->delta_days( $datetime )
1016
1017 Each of these methods returns a new "DateTime::Duration" object
1018 representing some portion of the difference between two datetimes. The
1019 "delta_md()" method returns a duration which contains only the month
1020 and day portions of the duration is represented. The "delta_days()"
1021 method returns a duration which contains only days.
1022
1023 The "delta_md" and "delta_days" methods truncate the duration so that
1024 any fractional portion of a day is ignored. Both of these methods
1025 operate on the date portion of a datetime only, and so effectively
1026 ignore the time zone.
1027
1028 Unlike the subtraction methods, these methods always return a positive
1029 (or zero) duration.
1030
1031 $dt->delta_ms( $datetime )
1032
1033 Returns a duration which contains only minutes and seconds. Any day and
1034 month differences to minutes are converted to minutes and seconds. This
1035 method also always return a positive (or zero) duration.
1036
1037 $dt->subtract_datetime_absolute( $datetime )
1038
1039 This method returns a new "DateTime::Duration" object representing the
1040 difference between the two dates in seconds and nanoseconds. This is
1041 the only way to accurately measure the absolute amount of time between
1042 two datetimes, since units larger than a second do not represent a
1043 fixed number of seconds.
1044
1045 Note that because of leap seconds, this may not return the same result
1046 as doing this math based on the value returned by "$dt->epoch()".
1047
1048 Class Methods
1049 DateTime->DefaultLocale( $locale )
1050
1051 This can be used to specify the default locale to be used when creating
1052 DateTime objects. If unset, then "en-US" is used.
1053
1054 DateTime->compare( $dt1, $dt2 ), DateTime->compare_ignore_floating(
1055 $dt1, $dt2 )
1056
1057 $cmp = DateTime->compare( $dt1, $dt2 );
1058
1059 $cmp = DateTime->compare_ignore_floating( $dt1, $dt2 );
1060
1061 Compare two DateTime objects. The semantics are compatible with Perl's
1062 "sort()" function; it returns -1 if $dt1 < $dt2, 0 if $dt1 == $dt2, 1
1063 if $dt1 > $dt2.
1064
1065 If one of the two DateTime objects has a floating time zone, it will
1066 first be converted to the time zone of the other object. This is what
1067 you want most of the time, but it can lead to inconsistent results when
1068 you compare a number of DateTime objects, some of which are floating,
1069 and some of which are in other time zones.
1070
1071 If you want to have consistent results (because you want to sort a
1072 number of objects, for example), you can use the
1073 "compare_ignore_floating()" method:
1074
1075 @dates = sort { DateTime->compare_ignore_floating($a, $b) } @dates;
1076
1077 In this case, objects with a floating time zone will be sorted as if
1078 they were UTC times.
1079
1080 Since DateTime objects overload comparison operators, this:
1081
1082 @dates = sort @dates;
1083
1084 is equivalent to this:
1085
1086 @dates = sort { DateTime->compare($a, $b) } @dates;
1087
1088 DateTime objects can be compared to any other calendar class that
1089 implements the "utc_rd_values()" method.
1090
1091 Testing Code That Uses DateTime
1092 If you are trying to test code that calls uses DateTime, you may want
1093 to be able to explicitly set the value returned by Perl's "time()"
1094 builtin. This builtin is called by "DateTime->now()" and
1095 "DateTime->today()".
1096
1097 You can override "CORE::GLOBAL::time()", but this will only work if
1098 you do this before loading DateTime. If doing this is inconvenient,
1099 you can also override "DateTime::_core_time()":
1100
1101 no warnings 'redefine';
1102 local *DateTime::_core_time = sub { return 42 };
1103
1104 DateTime is guaranteed to call this subroutine to get the current
1105 "time()" value. You can also override the "_core_time()" sub in a
1106 subclass of DateTime and use that.
1107
1108 How DateTime Math Works
1109 It's important to have some understanding of how datetime math is
1110 implemented in order to effectively use this module and
1111 "DateTime::Duration".
1112
1113 Making Things Simple
1114
1115 If you want to simplify your life and not have to think too hard about
1116 the nitty-gritty of datetime math, I have several recommendations:
1117
1118 · use the floating time zone
1119
1120 If you do not care about time zones or leap seconds, use the
1121 "floating" timezone:
1122
1123 my $dt = DateTime->now( time_zone => 'floating' );
1124
1125 Math done on two objects in the floating time zone produces very
1126 predictable results.
1127
1128 Note that in most cases you will want to start by creating an
1129 object in a specific zone and then convert it to the floating time
1130 zone. When an object goes from a real zone to the floating zone,
1131 the time for the object remains the same.
1132
1133 This means that passing the floating zone to a constructor may not
1134 do what you want.
1135
1136 my $dt = DateTime->now( time_zone => 'floating' );
1137
1138 is equivalent to
1139
1140 my $dt = DateTime->now( time_zone => 'UTC' )->set_time_zone('floating');
1141
1142 This might not be what you wanted. Instead, you may prefer to do
1143 this:
1144
1145 my $dt = DateTime->now( time_zone => 'local' )->set_time_zone('floating');
1146
1147 · use UTC for all calculations
1148
1149 If you do care about time zones (particularly DST) or leap seconds,
1150 try to use non-UTC time zones for presentation and user input only.
1151 Convert to UTC immediately and convert back to the local time zone
1152 for presentation:
1153
1154 my $dt = DateTime->new( %user_input, time_zone => $user_tz );
1155 $dt->set_time_zone('UTC');
1156
1157 # do various operations - store it, retrieve it, add, subtract, etc.
1158
1159 $dt->set_time_zone($user_tz);
1160 print $dt->datetime;
1161
1162 · math on non-UTC time zones
1163
1164 If you need to do date math on objects with non-UTC time zones,
1165 please read the caveats below carefully. The results "DateTime.pm"
1166 produces are predictable and correct, and mostly intuitive, but
1167 datetime math gets very ugly when time zones are involved, and
1168 there are a few strange corner cases involving subtraction of two
1169 datetimes across a DST change.
1170
1171 If you can always use the floating or UTC time zones, you can skip
1172 ahead to "Leap Seconds and Date Math"
1173
1174 · date vs datetime math
1175
1176 If you only care about the date (calendar) portion of a datetime,
1177 you should use either "delta_md()" or "delta_days()", not
1178 "subtract_datetime()". This will give predictable, unsurprising
1179 results, free from DST-related complications.
1180
1181 · subtract_datetime() and add_duration()
1182
1183 You must convert your datetime objects to the UTC time zone before
1184 doing date math if you want to make sure that the following
1185 formulas are always true:
1186
1187 $dt2 - $dt1 = $dur
1188 $dt1 + $dur = $dt2
1189 $dt2 - $dur = $dt1
1190
1191 Note that using "delta_days" ensures that this formula always
1192 works, regardless of the timezone of the objects involved, as does
1193 using "subtract_datetime_absolute()". Other methods of subtraction
1194 are not always reversible.
1195
1196 · never do math on two objects where only one is in the floating time
1197 zone
1198
1199 The date math code accounts for leap seconds whenever the
1200 "DateTime" object is not in the floating time zone. If you try to
1201 do math where one object is in the floating zone and the other
1202 isn't, the results will be confusing and wrong.
1203
1204 Adding a Duration to a Datetime
1205
1206 The parts of a duration can be broken down into five parts. These are
1207 months, days, minutes, seconds, and nanoseconds. Adding one month to a
1208 date is different than adding 4 weeks or 28, 29, 30, or 31 days.
1209 Similarly, due to DST and leap seconds, adding a day can be different
1210 than adding 86,400 seconds, and adding a minute is not exactly the same
1211 as 60 seconds.
1212
1213 We cannot convert between these units, except for seconds and
1214 nanoseconds, because there is no fixed conversion between the two
1215 units, because of things like leap seconds, DST changes, etc.
1216
1217 "DateTime.pm" always adds (or subtracts) days, then months, minutes,
1218 and then seconds and nanoseconds. If there are any boundary overflows,
1219 these are normalized at each step. For the days and months the local
1220 (not UTC) values are used. For minutes and seconds, the local values
1221 are used. This generally just works.
1222
1223 This means that adding one month and one day to February 28, 2003 will
1224 produce the date April 1, 2003, not March 29, 2003.
1225
1226 my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
1227
1228 $dt->add( months => 1, days => 1 );
1229
1230 # 2003-04-01 - the result
1231
1232 On the other hand, if we add months first, and then separately add
1233 days, we end up with March 29, 2003:
1234
1235 $dt->add( months => 1 )->add( days => 1 );
1236
1237 # 2003-03-29
1238
1239 We see similar strangeness when math crosses a DST boundary:
1240
1241 my $dt = DateTime->new(
1242 year => 2003,
1243 month => 4,
1244 day => 5,
1245 hour => 1,
1246 minute => 58,
1247 time_zone => "America/Chicago",
1248 );
1249
1250 $dt->add( days => 1, minutes => 3 );
1251 # 2003-04-06 02:01:00
1252
1253 $dt->add( minutes => 3 )->add( days => 1 );
1254 # 2003-04-06 03:01:00
1255
1256 Note that if you converted the datetime object to UTC first you would
1257 get predictable results.
1258
1259 If you want to know how many seconds a duration object represents, you
1260 have to add it to a datetime to find out, so you could do:
1261
1262 my $now = DateTime->now( time_zone => 'UTC' );
1263 my $later = $now->clone->add_duration($duration);
1264
1265 my $seconds_dur = $later->subtract_datetime_absolute($now);
1266
1267 This returns a duration which only contains seconds and nanoseconds.
1268
1269 If we were add the duration to a different datetime object we might get
1270 a different number of seconds.
1271
1272 DateTime::Duration supports three different end-of-month algorithms for
1273 adding months. This comes into play when an addition results in a day
1274 past the end of the month (for example, adding one month to January
1275 30).
1276
1277 # 2010-08-31 + 1 month = 2010-10-01
1278 $dt->add( months => 1, end_of_month => 'wrap' );
1279
1280 # 2010-01-30 + 1 month = 2010-02-28
1281 $dt->add( months => 1, end_of_month => 'limit' );
1282
1283 # 2010-04-30 + 1 month = 2010-05-31
1284 $dt->add( months => 1, end_of_month => 'preserve' );
1285
1286 By default, it uses "wrap" for positive durations and "preserve" for
1287 negative durations. See DateTime::Duration for a detailed explanation
1288 of these algorithms.
1289
1290 If you need to do lots of work with durations, take a look at Rick
1291 Measham's "DateTime::Format::Duration" module, which lets you present
1292 information from durations in many useful ways.
1293
1294 There are other subtract/delta methods in DateTime.pm to generate
1295 different types of durations. These methods are "subtract_datetime()",
1296 "subtract_datetime_absolute()", "delta_md()", "delta_days()", and
1297 "delta_ms()".
1298
1299 Datetime Subtraction
1300
1301 Date subtraction is done solely based on the two object's local
1302 datetimes, with one exception to handle DST changes. Also, if the two
1303 datetime objects are in different time zones, one of them is converted
1304 to the other's time zone first before subtraction. This is best
1305 explained through examples:
1306
1307 The first of these probably makes the most sense:
1308
1309 my $dt1 = DateTime->new(
1310 year => 2003,
1311 month => 5,
1312 day => 6,
1313 time_zone => 'America/Chicago',
1314 );
1315
1316 # not DST
1317
1318 my $dt2 = DateTime->new(
1319 year => 2003,
1320 month => 11,
1321 day => 6,
1322 time_zone => 'America/Chicago',
1323 );
1324
1325 # is DST
1326
1327 my $dur = $dt2->subtract_datetime($dt1);
1328 # 6 months
1329
1330 Nice and simple.
1331
1332 This one is a little trickier, but still fairly logical:
1333
1334 my $dt1 = DateTime->new(
1335 year => 2003,
1336 month => 4,
1337 day => 5,
1338 hour => 1,
1339 minute => 58,
1340 time_zone => "America/Chicago",
1341 );
1342
1343 # is DST
1344
1345 my $dt2 = DateTime->new(
1346 year => 2003,
1347 month => 4,
1348 day => 7,
1349 hour => 2,
1350 minute => 1,
1351 time_zone => "America/Chicago",
1352 );
1353
1354 # not DST
1355
1356 my $dur = $dt2->subtract_datetime($dt1);
1357
1358 # 2 days and 3 minutes
1359
1360 Which contradicts the result this one gives, even though they both make
1361 sense:
1362
1363 my $dt1 = DateTime->new(
1364 year => 2003,
1365 month => 4,
1366 day => 5,
1367 hour => 1,
1368 minute => 58,
1369 time_zone => "America/Chicago",
1370 );
1371
1372 # is DST
1373
1374 my $dt2 = DateTime->new(
1375 year => 2003,
1376 month => 4,
1377 day => 6,
1378 hour => 3,
1379 minute => 1,
1380 time_zone => "America/Chicago",
1381 );
1382
1383 # not DST
1384
1385 my $dur = $dt2->subtract_datetime($dt1);
1386
1387 # 1 day and 3 minutes
1388
1389 This last example illustrates the "DST" exception mentioned earlier.
1390 The exception accounts for the fact 2003-04-06 only lasts 23 hours.
1391
1392 And finally:
1393
1394 my $dt2 = DateTime->new(
1395 year => 2003,
1396 month => 10,
1397 day => 26,
1398 hour => 1,
1399 time_zone => 'America/Chicago',
1400 );
1401
1402 my $dt1 = $dt2->clone->subtract( hours => 1 );
1403
1404 my $dur = $dt2->subtract_datetime($dt1);
1405 # 60 minutes
1406
1407 This seems obvious until you realize that subtracting 60 minutes from
1408 $dt2 in the above example still leaves the clock time at "01:00:00".
1409 This time we are accounting for a 25 hour day.
1410
1411 Reversibility
1412
1413 Date math operations are not always reversible. This is because of the
1414 way that addition operations are ordered. As was discussed earlier,
1415 adding 1 day and 3 minutes in one call to "add()" is not the same as
1416 first adding 3 minutes and 1 day in two separate calls.
1417
1418 If we take a duration returned from "subtract_datetime()" and then try
1419 to add or subtract that duration from one of the datetimes we just
1420 used, we sometimes get interesting results:
1421
1422 my $dt1 = DateTime->new(
1423 year => 2003,
1424 month => 4,
1425 day => 5,
1426 hour => 1,
1427 minute => 58,
1428 time_zone => "America/Chicago",
1429 );
1430
1431 my $dt2 = DateTime->new(
1432 year => 2003,
1433 month => 4,
1434 day => 6,
1435 hour => 3,
1436 minute => 1,
1437 time_zone => "America/Chicago",
1438 );
1439
1440 my $dur = $dt2->subtract_datetime($dt1);
1441 # 1 day and 3 minutes
1442
1443 $dt1->add_duration($dur);
1444 # gives us $dt2
1445
1446 $dt2->subtract_duration($dur);
1447 # gives us 2003-04-05 02:58:00 - 1 hour later than $dt1
1448
1449 The "subtract_duration()" operation gives us a (perhaps) unexpected
1450 answer because it first subtracts one day to get 2003-04-05T03:01:00
1451 and then subtracts 3 minutes to get the final result.
1452
1453 If we explicitly reverse the order we can get the original value of
1454 $dt1. This can be facilitated by "DateTime::Duration"'s
1455 "calendar_duration()" and "clock_duration()" methods:
1456
1457 $dt2->subtract_duration( $dur->clock_duration )
1458 ->subtract_duration( $dur->calendar_duration );
1459
1460 Leap Seconds and Date Math
1461
1462 The presence of leap seconds can cause even more anomalies in date
1463 math. For example, the following is a legal datetime:
1464
1465 my $dt = DateTime->new(
1466 year => 1972,
1467 month => 12,
1468 day => 31,
1469 hour => 23,
1470 minute => 59,
1471 second => 60,
1472 time_zone => 'UTC'
1473 );
1474
1475 If we do the following:
1476
1477 $dt->add( months => 1 );
1478
1479 Then the datetime is now "1973-02-01 00:00:00", because there is no
1480 23:59:60 on 1973-01-31.
1481
1482 Leap seconds also force us to distinguish between minutes and seconds
1483 during date math. Given the following datetime:
1484
1485 my $dt = DateTime->new(
1486 year => 1972,
1487 month => 12,
1488 day => 31,
1489 hour => 23,
1490 minute => 59,
1491 second => 30,
1492 time_zone => 'UTC'
1493 );
1494
1495 we will get different results when adding 1 minute than we get if we
1496 add 60 seconds. This is because in this case, the last minute of the
1497 day, beginning at 23:59:00, actually contains 61 seconds.
1498
1499 Here are the results we get:
1500
1501 # 1972-12-31 23:59:30 - our starting datetime
1502
1503 $dt->clone->add( minutes => 1 );
1504 # 1973-01-01 00:00:30 - one minute later
1505
1506 $dt->clone->add( seconds => 60 );
1507 # 1973-01-01 00:00:29 - 60 seconds later
1508
1509 $dt->clone->add( seconds => 61 );
1510 # 1973-01-01 00:00:30 - 61 seconds later
1511
1512 Local vs. UTC and 24 hours vs. 1 day
1513
1514 When math crosses a daylight saving boundary, a single day may have
1515 more or less than 24 hours.
1516
1517 For example, if you do this:
1518
1519 my $dt = DateTime->new(
1520 year => 2003,
1521 month => 4,
1522 day => 5,
1523 hour => 2,
1524 time_zone => 'America/Chicago',
1525 );
1526
1527 $dt->add( days => 1 );
1528
1529 then you will produce an invalid local time, and therefore an exception
1530 will be thrown.
1531
1532 However, this works:
1533
1534 my $dt = DateTime->new(
1535 year => 2003,
1536 month => 4,
1537 day => 5,
1538 hour => 2,
1539 time_zone => 'America/Chicago',
1540 );
1541
1542 $dt->add( hours => 24 );
1543
1544 and produces a datetime with the local time of "03:00".
1545
1546 If all this makes your head hurt, there is a simple alternative. Just
1547 convert your datetime object to the "UTC" time zone before doing date
1548 math on it, and switch it back to the local time zone afterwards. This
1549 avoids the possibility of having date math throw an exception, and
1550 makes sure that 1 day equals 24 hours. Of course, this may not always
1551 be desirable, so caveat user!
1552
1553 Overloading
1554 This module explicitly overloads the addition (+), subtraction (-),
1555 string and numeric comparison operators. This means that the following
1556 all do sensible things:
1557
1558 my $new_dt = $dt + $duration_obj;
1559
1560 my $new_dt = $dt - $duration_obj;
1561
1562 my $duration_obj = $dt - $new_dt;
1563
1564 foreach my $dt ( sort @dts ) { ... }
1565
1566 Additionally, the fallback parameter is set to true, so other derivable
1567 operators (+=, -=, etc.) will work properly. Do not expect increment
1568 (++) or decrement (--) to do anything useful.
1569
1570 The string comparison operators, "eq" or "ne", will use the string
1571 value to compare with non-DateTime objects.
1572
1573 DateTime objects do not have a numeric value, using "==" or "<=>" to
1574 compare a DateTime object with a non-DateTime object will result in an
1575 exception. To safely sort mixed DateTime and non-DateTime objects, use
1576 "sort { $a cmp $b } @dates".
1577
1578 The module also overloads stringification using the object's formatter,
1579 defaulting to "iso8601()" method. See "Formatters And Stringification"
1580 for details.
1581
1582 Formatters And Stringification
1583 You can optionally specify a "formatter", which is usually a
1584 DateTime::Format::* object/class, to control the stringification of the
1585 DateTime object.
1586
1587 Any of the constructor methods can accept a formatter argument:
1588
1589 my $formatter = DateTime::Format::Strptime->new(...);
1590 my $dt = DateTime->new(year => 2004, formatter => $formatter);
1591
1592 Or, you can set it afterwards:
1593
1594 $dt->set_formatter($formatter);
1595 $formatter = $dt->formatter();
1596
1597 Once you set the formatter, the overloaded stringification method will
1598 use the formatter. If unspecified, the "iso8601()" method is used.
1599
1600 A formatter can be handy when you know that in your application you
1601 want to stringify your DateTime objects into a special format all the
1602 time, for example to a different language.
1603
1604 If you provide a formatter class name or object, it must implement a
1605 "format_datetime" method. This method will be called with just the
1606 DateTime object as its argument.
1607
1608 CLDR Patterns
1609 The CLDR pattern language is both more powerful and more complex than
1610 strftime. Unlike strftime patterns, you often have to explicitly escape
1611 text that you do not want formatted, as the patterns are simply letters
1612 without any prefix.
1613
1614 For example, "yyyy-MM-dd" is a valid CLDR pattern. If you want to
1615 include any lower or upper case ASCII characters as-is, you can
1616 surround them with single quotes ('). If you want to include a single
1617 quote, you must escape it as two single quotes ('').
1618
1619 'Today is ' EEEE
1620 'It is now' h 'o''clock' a
1621
1622 Spaces and any non-letter text will always be passed through as-is.
1623
1624 Many CLDR patterns which produce numbers will pad the number with
1625 leading zeroes depending on the length of the format specifier. For
1626 example, "h" represents the current hour from 1-12. If you specify "hh"
1627 then the 1-9 will have a leading zero prepended.
1628
1629 However, CLDR often uses five of a letter to represent the narrow form
1630 of a pattern. This inconsistency is necessary for backwards
1631 compatibility.
1632
1633 CLDR often distinguishes between the "format" and "stand-alone" forms
1634 of a pattern. The format pattern is used when the thing in question is
1635 being placed into a larger string. The stand-alone form is used when
1636 displaying that item by itself, for example in a calendar.
1637
1638 It also often provides three sizes for each item, wide (the full name),
1639 abbreviated, and narrow. The narrow form is often just a single
1640 character, for example "T" for "Tuesday", and may not be unique.
1641
1642 CLDR provides a fairly complex system for localizing time zones that we
1643 ignore entirely. The time zone patterns just use the information
1644 provided by "DateTime::TimeZone", and do not follow the CLDR spec.
1645
1646 The output of a CLDR pattern is always localized, when applicable.
1647
1648 CLDR provides the following patterns:
1649
1650 · G{1,3}
1651
1652 The abbreviated era (BC, AD).
1653
1654 · GGGG
1655
1656 The wide era (Before Christ, Anno Domini).
1657
1658 · GGGGG
1659
1660 The narrow era, if it exists (and it mostly doesn't).
1661
1662 · y and y{3,}
1663
1664 The year, zero-prefixed as needed. Negative years will start with a
1665 "-", and this will be included in the length calculation.
1666
1667 In other, words the "yyyyy" pattern will format year -1234 as
1668 "-1234", not "-01234".
1669
1670 · yy
1671
1672 This is a special case. It always produces a two-digit year, so
1673 "1976" becomes "76". Negative years will start with a "-", making
1674 them one character longer.
1675
1676 · Y{1,}
1677
1678 The year in "week of the year" calendars, from "$dt->week_year()".
1679
1680 · u{1,}
1681
1682 Same as "y" except that "uu" is not a special case.
1683
1684 · Q{1,2}
1685
1686 The quarter as a number (1..4).
1687
1688 · QQQ
1689
1690 The abbreviated format form for the quarter.
1691
1692 · QQQQ
1693
1694 The wide format form for the quarter.
1695
1696 · q{1,2}
1697
1698 The quarter as a number (1..4).
1699
1700 · qqq
1701
1702 The abbreviated stand-alone form for the quarter.
1703
1704 · qqqq
1705
1706 The wide stand-alone form for the quarter.
1707
1708 · M{1,2]
1709
1710 The numerical month.
1711
1712 · MMM
1713
1714 The abbreviated format form for the month.
1715
1716 · MMMM
1717
1718 The wide format form for the month.
1719
1720 · MMMMM
1721
1722 The narrow format form for the month.
1723
1724 · L{1,2]
1725
1726 The numerical month.
1727
1728 · LLL
1729
1730 The abbreviated stand-alone form for the month.
1731
1732 · LLLL
1733
1734 The wide stand-alone form for the month.
1735
1736 · LLLLL
1737
1738 The narrow stand-alone form for the month.
1739
1740 · w{1,2}
1741
1742 The week of the year, from "$dt->week_number()".
1743
1744 · W
1745
1746 The week of the month, from "$dt->week_of_month()".
1747
1748 · d{1,2}
1749
1750 The numeric day of the month.
1751
1752 · D{1,3}
1753
1754 The numeric day of the year.
1755
1756 · F
1757
1758 The day of the week in the month, from "$dt->weekday_of_month()".
1759
1760 · g{1,}
1761
1762 The modified Julian day, from "$dt->mjd()".
1763
1764 · E{1,3} and eee
1765
1766 The abbreviated format form for the day of the week.
1767
1768 · EEEE and eeee
1769
1770 The wide format form for the day of the week.
1771
1772 · EEEEE and eeeee
1773
1774 The narrow format form for the day of the week.
1775
1776 · e{1,2}
1777
1778 The local numeric day of the week, from 1 to 7. This number depends
1779 on what day is considered the first day of the week, which varies
1780 by locale. For example, in the US, Sunday is the first day of the
1781 week, so this returns 2 for Monday.
1782
1783 · c
1784
1785 The numeric day of the week from 1 to 7, treating Monday as the
1786 first of the week, regardless of locale.
1787
1788 · ccc
1789
1790 The abbreviated stand-alone form for the day of the week.
1791
1792 · cccc
1793
1794 The wide stand-alone form for the day of the week.
1795
1796 · ccccc
1797
1798 The narrow format form for the day of the week.
1799
1800 · a
1801
1802 The localized form of AM or PM for the time.
1803
1804 · h{1,2}
1805
1806 The hour from 1-12.
1807
1808 · H{1,2}
1809
1810 The hour from 0-23.
1811
1812 · K{1,2}
1813
1814 The hour from 0-11.
1815
1816 · k{1,2}
1817
1818 The hour from 1-24.
1819
1820 · j{1,2}
1821
1822 The hour, in 12 or 24 hour form, based on the preferred form for
1823 the locale. In other words, this is equivalent to either "h{1,2}"
1824 or "H{1,2}".
1825
1826 · m{1,2}
1827
1828 The minute.
1829
1830 · s{1,2}
1831
1832 The second.
1833
1834 · S{1,}
1835
1836 The fractional portion of the seconds, rounded based on the length
1837 of the specifier. This returned without a leading decimal point,
1838 but may have leading or trailing zeroes.
1839
1840 · A{1,}
1841
1842 The millisecond of the day, based on the current time. In other
1843 words, if it is 12:00:00.00, this returns 43200000.
1844
1845 · z{1,3}
1846
1847 The time zone short name.
1848
1849 · zzzz
1850
1851 The time zone long name.
1852
1853 · Z{1,3}
1854
1855 The time zone offset.
1856
1857 · ZZZZ
1858
1859 The time zone short name and the offset as one string, so something
1860 like "CDT-0500".
1861
1862 · ZZZZZ
1863
1864 The time zone offset as a sexagesimal number, so something like
1865 "-05:00". (This is useful for W3C format.)
1866
1867 · v{1,3}
1868
1869 The time zone short name.
1870
1871 · vvvv
1872
1873 The time zone long name.
1874
1875 · V{1,3}
1876
1877 The time zone short name.
1878
1879 · VVVV
1880
1881 The time zone long name.
1882
1883 CLDR "Available Formats"
1884
1885 The CLDR data includes pre-defined formats for various patterns such as
1886 "month and day" or "time of day". Using these formats lets you render
1887 information about a datetime in the most natural way for users from a
1888 given locale.
1889
1890 These formats are indexed by a key that is itself a CLDR pattern. When
1891 you look these up, you get back a different CLDR pattern suitable for
1892 the locale.
1893
1894 Let's look at some example We'll use "2008-02-05T18:30:30" as our
1895 example datetime value, and see how this is rendered for the "en-US"
1896 and "fr-FR" locales.
1897
1898 · "MMMd"
1899
1900 The abbreviated month and day as number. For "en-US", we get the
1901 pattern "MMM d", which renders as "Feb 5". For "fr-FR", we get the
1902 pattern "d MMM", which renders as "5 févr.".
1903
1904 · "yQQQ"
1905
1906 The year and abbreviated quarter of year. For "en-US", we get the
1907 pattern "QQQ y", which renders as "Q1 2008". For "fr-FR", we get
1908 the same pattern, "QQQ y", which renders as "T1 2008".
1909
1910 · "hm"
1911
1912 The 12-hour time of day without seconds. For "en-US", we get the
1913 pattern "h:mm a", which renders as "6:30 PM". For "fr-FR", we get
1914 the exact same pattern and rendering.
1915
1916 The available formats for each locale are documented in the POD for
1917 that locale. To get back the format, you use the "$locale->format_for"
1918 method. For example:
1919
1920 say $dt->format_cldr( $dt->locale->format_for('MMMd') );
1921
1922 strftime Patterns
1923 The following patterns are allowed in the format string given to the
1924 "$dt->strftime()" method:
1925
1926 · %a
1927
1928 The abbreviated weekday name.
1929
1930 · %A
1931
1932 The full weekday name.
1933
1934 · %b
1935
1936 The abbreviated month name.
1937
1938 · %B
1939
1940 The full month name.
1941
1942 · %c
1943
1944 The default datetime format for the object's locale.
1945
1946 · %C
1947
1948 The century number (year/100) as a 2-digit integer.
1949
1950 · %d
1951
1952 The day of the month as a decimal number (range 01 to 31).
1953
1954 · %D
1955
1956 Equivalent to %m/%d/%y. This is not a good standard format if you
1957 want folks from both the United States and the rest of the world to
1958 understand the date!
1959
1960 · %e
1961
1962 Like %d, the day of the month as a decimal number, but a leading
1963 zero is replaced by a space.
1964
1965 · %F
1966
1967 Equivalent to %Y-%m-%d (the ISO 8601 date format)
1968
1969 · %G
1970
1971 The ISO 8601 year with century as a decimal number. The 4-digit
1972 year corresponding to the ISO week number (see %V). This has the
1973 same format and value as %Y, except that if the ISO week number
1974 belongs to the previous or next year, that year is used instead.
1975 (TZ)
1976
1977 · %g
1978
1979 Like %G, but without century, i.e., with a 2-digit year (00-99).
1980
1981 · %h
1982
1983 Equivalent to %b.
1984
1985 · %H
1986
1987 The hour as a decimal number using a 24-hour clock (range 00 to
1988 23).
1989
1990 · %I
1991
1992 The hour as a decimal number using a 12-hour clock (range 01 to
1993 12).
1994
1995 · %j
1996
1997 The day of the year as a decimal number (range 001 to 366).
1998
1999 · %k
2000
2001 The hour (24-hour clock) as a decimal number (range 0 to 23);
2002 single digits are preceded by a blank. (See also %H.)
2003
2004 · %l
2005
2006 The hour (12-hour clock) as a decimal number (range 1 to 12);
2007 single digits are preceded by a blank. (See also %I.)
2008
2009 · %m
2010
2011 The month as a decimal number (range 01 to 12).
2012
2013 · %M
2014
2015 The minute as a decimal number (range 00 to 59).
2016
2017 · %n
2018
2019 A newline character.
2020
2021 · %N
2022
2023 The fractional seconds digits. Default is 9 digits (nanoseconds).
2024
2025 %3N milliseconds (3 digits)
2026 %6N microseconds (6 digits)
2027 %9N nanoseconds (9 digits)
2028
2029 This value will always be rounded down to the nearest integer.
2030
2031 · %p
2032
2033 Either `AM' or `PM' according to the given time value, or the
2034 corresponding strings for the current locale. Noon is treated as
2035 `pm' and midnight as `am'.
2036
2037 · %P
2038
2039 Like %p but in lowercase: `am' or `pm' or a corresponding string
2040 for the current locale.
2041
2042 · %r
2043
2044 The time in a.m. or p.m. notation. In the POSIX locale this is
2045 equivalent to `%I:%M:%S %p'.
2046
2047 · %R
2048
2049 The time in 24-hour notation (%H:%M). (SU) For a version including
2050 the seconds, see %T below.
2051
2052 · %s
2053
2054 The number of seconds since the epoch.
2055
2056 · %S
2057
2058 The second as a decimal number (range 00 to 61).
2059
2060 · %t
2061
2062 A tab character.
2063
2064 · %T
2065
2066 The time in 24-hour notation (%H:%M:%S).
2067
2068 · %u
2069
2070 The day of the week as a decimal, range 1 to 7, Monday being 1. See
2071 also %w.
2072
2073 · %U
2074
2075 The week number of the current year as a decimal number, range 00
2076 to 53, starting with the first Sunday as the first day of week 01.
2077 See also %V and %W.
2078
2079 · %V
2080
2081 The ISO 8601:1988 week number of the current year as a decimal
2082 number, range 01 to 53, where week 1 is the first week that has at
2083 least 4 days in the current year, and with Monday as the first day
2084 of the week. See also %U and %W.
2085
2086 · %w
2087
2088 The day of the week as a decimal, range 0 to 6, Sunday being 0. See
2089 also %u.
2090
2091 · %W
2092
2093 The week number of the current year as a decimal number, range 00
2094 to 53, starting with the first Monday as the first day of week 01.
2095
2096 · %x
2097
2098 The default date format for the object's locale.
2099
2100 · %X
2101
2102 The default time format for the object's locale.
2103
2104 · %y
2105
2106 The year as a decimal number without a century (range 00 to 99).
2107
2108 · %Y
2109
2110 The year as a decimal number including the century.
2111
2112 · %z
2113
2114 The time-zone as hour offset from UTC. Required to emit
2115 RFC822-conformant dates (using "%a, %d %b %Y %H:%M:%S %z").
2116
2117 · %Z
2118
2119 The short name for the time zone, typically an abbreviation like
2120 "EST" or "AEST".
2121
2122 · %%
2123
2124 A literal `%' character.
2125
2126 · %{method}
2127
2128 Any method name may be specified using the format "%{method}" name
2129 where "method" is a valid "DateTime.pm" object method.
2130
2131 DateTime.pm and Storable
2132 DateTime implements Storable hooks in order to reduce the size of a
2133 serialized DateTime object.
2134
2136 This module is part of a larger ecosystem of modules in the DateTime
2137 family.
2138
2139 DateTime::Set
2140 The DateTime::Set module represents sets (including recurrences) of
2141 datetimes. Many modules return sets or recurrences.
2142
2143 Format Modules
2144 The various format modules exist to parse and format datetimes. For
2145 example, DateTime::Format::HTTP parses dates according to the RFC 1123
2146 format:
2147
2148 my $datetime
2149 = DateTime::Format::HTTP->parse_datetime('Thu Feb 3 17:03:55 GMT 1994');
2150
2151 print DateTime::Format::HTTP->format_datetime($datetime);
2152
2153 Most format modules are suitable for use as a "formatter" with a
2154 DateTime object.
2155
2156 All format modules start with "DateTime::Format::".
2157
2158 Calendar Modules
2159 There are a number of modules on CPAN that implement non-Gregorian
2160 calendars, such as the Chinese, Mayan, and Julian calendars.
2161
2162 All calendar modules start with "DateTime::Calendar::".
2163
2164 Event Modules
2165 There are a number of modules that calculate the dates for events, such
2166 as Easter, Sunrise, etc.
2167
2168 All event modules start with "DateTime::Event::".
2169
2170 Others
2171 There are many other modules that work with DateTime, including modules
2172 in the "DateTimeX" namespace, as well as others.
2173
2174 See the datetime wiki <http://datetime.perl.org> and search.cpan.org
2175 <http://search.cpan.org/search?query=datetime&mode=dist> for more
2176 details.
2177
2179 The tests in 20infinite.t seem to fail on some machines, particularly
2180 on Win32. This appears to be related to Perl's internal handling of
2181 IEEE infinity and NaN, and seems to be highly platform/compiler/phase
2182 of moon dependent.
2183
2184 If you don't plan to use infinite datetimes you can probably ignore
2185 this. This will be fixed (perhaps) in future versions.
2186
2188 A Date with Perl <http://www.houseabsolute.com/presentations/a-date-
2189 with-perl/> - a talk I've given at a few YAPCs.
2190
2191 datetime@perl.org mailing list
2192 <http://lists.perl.org/list/datetime.html>
2193
2194 <http://datetime.perl.org/>
2195
2197 Bugs may be submitted at
2198 <https://github.com/houseabsolute/DateTime.pm/issues>.
2199
2200 There is a mailing list available for users of this distribution,
2201 <mailto:datetime@perl.org>.
2202
2203 I am also usually active on IRC as 'autarch' on "irc://irc.perl.org".
2204
2206 The source code repository for DateTime can be found at
2207 <https://github.com/houseabsolute/DateTime.pm>.
2208
2210 If you'd like to thank me for the work I've done on this module, please
2211 consider making a "donation" to me via PayPal. I spend a lot of free
2212 time creating free software, and would appreciate any support you'd
2213 care to offer.
2214
2215 Please note that I am not suggesting that you must do this in order for
2216 me to continue working on this particular software. I will continue to
2217 do so, inasmuch as I have in the past, for as long as it interests me.
2218
2219 Similarly, a donation made in this way will probably not make me work
2220 on this software much more, unless I get so many donations that I can
2221 consider working on free software full time (let's all have a chuckle
2222 at that together).
2223
2224 To donate, log into PayPal and send money to autarch@urth.org, or use
2225 the button at <http://www.urth.org/~autarch/fs-donation.html>.
2226
2228 Dave Rolsky <autarch@urth.org>
2229
2231 · Ben Bennett <fiji@limey.net>
2232
2233 · Christian Hansen <chansen@cpan.org>
2234
2235 · Daisuke Maki <dmaki@cpan.org>
2236
2237 · Dan Book <grinnz@gmail.com>
2238
2239 · Dan Stewart <danielandrewstewart@gmail.com>
2240
2241 · David E. Wheeler <david@justatheory.com>
2242
2243 · David Precious <davidp@preshweb.co.uk>
2244
2245 · Doug Bell <madcityzen@gmail.com>
2246
2247 · Flávio Soibelmann Glock <fglock@gmail.com>
2248
2249 · Gianni Ceccarelli <gianni.ceccarelli@broadbean.com>
2250
2251 · Gregory Oschwald <oschwald@gmail.com>
2252
2253 · Hauke D <haukex@zero-g.net>
2254
2255 · Iain Truskett <deceased>
2256
2257 · Jason McIntosh <jmac@jmac.org>
2258
2259 · Joshua Hoblitt <jhoblitt@cpan.org>
2260
2261 · Karen Etheridge <ether@cpan.org>
2262
2263 · Michael Conrad <mike@nrdvana.net>
2264
2265 · Michael R. Davis <mrdvt92@users.noreply.github.com>
2266
2267 · Mohammad S Anwar <mohammad.anwar@yahoo.com>
2268
2269 · M Somerville <dracos@users.noreply.github.com>
2270
2271 · Nick Tonkin <1nickt@users.noreply.github.com>
2272
2273 · Olaf Alders <olaf@wundersolutions.com>
2274
2275 · Ovid <curtis_ovid_poe@yahoo.com>
2276
2277 · Paul Howarth <paul@city-fan.org>
2278
2279 · Philippe Bruhat (BooK) <book@cpan.org>
2280
2281 · Ricardo Signes <rjbs@cpan.org>
2282
2283 · Richard Bowen <bowen@cpan.org>
2284
2285 · Ron Hill <rkhill@cpan.org>
2286
2287 · Sam Kington <github@illuminated.co.uk>
2288
2289 · viviparous <viviparous@prc>
2290
2292 This software is Copyright (c) 2003 - 2019 by Dave Rolsky.
2293
2294 This is free software, licensed under:
2295
2296 The Artistic License 2.0 (GPL Compatible)
2297
2298 The full text of the license can be found in the LICENSE file included
2299 with this distribution.
2300
2301
2302
2303perl v5.30.0 2019-07-26 DateTime(3)