1DateTime(3)           User Contributed Perl Documentation          DateTime(3)
2
3
4

NAME

6       DateTime - A date and time object
7

SYNOPSIS

9         use DateTime;
10
11         $dt = DateTime->new( year   => 1964,
12                              month  => 10,
13                              day    => 16,
14                              hour   => 16,
15                              minute => 12,
16                              second => 47,
17                              nanosecond => 500000000,
18                              time_zone => 'Asia/Taipei',
19                            );
20
21         $dt = DateTime->from_epoch( epoch => $epoch );
22         $dt = DateTime->now; # same as ( epoch => time() )
23
24         $year   = $dt->year;
25         $month  = $dt->month;          # 1-12 - also mon
26
27         $day    = $dt->day;            # 1-31 - also day_of_month, mday
28
29         $dow    = $dt->day_of_week;    # 1-7 (Monday is 1) - also dow, wday
30
31         $hour   = $dt->hour;           # 0-23
32         $minute = $dt->minute;         # 0-59 - also min
33
34         $second = $dt->second;         # 0-61 (leap seconds!) - also sec
35
36         $doy    = $dt->day_of_year;    # 1-366 (leap years) - also doy
37
38         $doq    = $dt->day_of_quarter; # 1.. - also doq
39
40         $qtr    = $dt->quarter;        # 1-4
41
42         # all of the start-at-1 methods above have correponding start-at-0
43         # methods, such as $dt->day_of_month_0, $dt->month_0 and so on
44
45         $ymd    = $dt->ymd;           # 2002-12-06
46         $ymd    = $dt->ymd('/');      # 2002/12/06 - also date
47
48         $mdy    = $dt->mdy;           # 12-06-2002
49         $mdy    = $dt->mdy('/');      # 12/06/2002
50
51         $dmy    = $dt->dmy;           # 06-12-2002
52         $dmy    = $dt->dmy('/');      # 06/12/2002
53
54         $hms    = $dt->hms;           # 14:02:29
55         $hms    = $dt->hms('!');      # 14!02!29 - also time
56
57         $is_leap  = $dt->is_leap_year;
58
59         # these are localizable, see Locales section
60         $month_name  = $dt->month_name; # January, February, ...
61         $month_abbr  = $dt->month_abbr; # Jan, Feb, ...
62         $day_name    = $dt->day_name;   # Monday, Tuesday, ...
63         $day_abbr    = $dt->day_abbr;   # Mon, Tue, ...
64
65         $epoch_time  = $dt->epoch;
66         # may return undef if the datetime is outside the range that is
67         # representable by your OS's epoch system.
68
69         $dt2 = $dt + $duration_object;
70
71         $dt3 = $dt - $duration_object;
72
73         $duration_object = $dt - $dt2;
74
75         $dt->set( year => 1882 );
76
77         $dt->set_time_zone( 'America/Chicago' );
78
79         $dt->set_formatter( $formatter );
80

DESCRIPTION

82       DateTime is a class for the representation of date/time combinations,
83       and is part of the Perl DateTime project.  For details on this project
84       please see <http://datetime.perl.org/>.  The DateTime site has a FAQ
85       which may help answer many "how do I do X?" questions.  The FAQ is at
86       <http://datetime.perl.org/faq.html>.
87
88       It represents the Gregorian calendar, extended backwards in time before
89       its creation (in 1582).  This is sometimes known as the "proleptic Gre‐
90       gorian calendar".  In this calendar, the first day of the calendar (the
91       epoch), is the first day of year 1, which corresponds to the date which
92       was (incorrectly) believed to be the birth of Jesus Christ.
93
94       The calendar represented does have a year 0, and in that way differs
95       from how dates are often written using "BCE/CE" or "BC/AD".
96
97       For infinite datetimes, please see the DateTime::Infinite module.
98

USAGE

100       0-based Versus 1-based Numbers
101
102       The DateTime.pm module follows a simple consistent logic for determin‐
103       ing whether or not a given number is 0-based or 1-based.
104
105       Month, day of month, day of week, and day of year are 1-based.  Any
106       method that is 1-based also has an equivalent 0-based method ending in
107       "_0".  So for example, this class provides both "day_of_week()" and
108       "day_of_week_0()" methods.
109
110       The "day_of_week_0()" method still treats Monday as the first day of
111       the week.
112
113       All time-related numbers such as hour, minute, and second are 0-based.
114
115       Years are neither, as they can be both positive or negative, unlike any
116       other datetime component.  There is a year 0.
117
118       There is no "quarter_0()" method.
119
120       Error Handling
121
122       Some errors may cause this module to die with an error string.  This
123       can only happen when calling constructor methods, methods that change
124       the object, such as "set()", or methods that take parameters.  Methods
125       that retrieve information about the object, such as "year()" or
126       "epoch()", will never die.
127
128       Locales
129
130       All the object methods which return names or abbreviations return data
131       based on a locale.  This is done by setting the locale when construct‐
132       ing a DateTime object.  There is also a "DefaultLocale()" class method
133       which may be used to set the default locale for all DateTime objects
134       created.  If this is not set, then "en_US" is used.
135
136       Some locales may return data as Unicode.  When using Perl 5.6.0 or
137       greater, this will be a native Perl Unicode string.  When using older
138       Perls, this will be a sequence of bytes representing the Unicode char‐
139       acter.
140
141       Floating DateTimes
142
143       The default time zone for new DateTime objects, except where stated
144       otherwise, is the "floating" time zone.  This concept comes from the
145       iCal standard.  A floating datetime is one which is not anchored to any
146       particular time zone.  In addition, floating datetimes do not include
147       leap seconds, since we cannot apply them without knowing the datetime's
148       time zone.
149
150       The results of date math and comparison between a floating datetime and
151       one with a real time zone are not really valid, because one includes
152       leap seconds and the other does not.  Similarly, the results of date‐
153       time math between two floating datetimes and two datetimes with time
154       zones are not really comparable.
155
156       If you are planning to use any objects with a real time zone, it is
157       strongly recommended that you do not mix these with floating datetimes.
158
159       Math
160
161       If you are going to be using doing date math, please read the section
162       How Datetime Math is Done.
163
164       Time Zone Warning
165
166       Do not try to use named time zones (like "America/Chicago") with dates
167       very far in the future (thousands of years). The current implementation
168       of "DateTime::TimeZone" will use a huge amount of memory calculating
169       all the DST changes from now until the future date. Use UTC or the
170       floating time zone and you will be safe.
171
172       Methods
173
174       Constructors
175
176       All constructors can die when invalid parameters are given.
177
178       * new( ... )
179           This class method accepts parameters for each date and time compo‐
180           nent: "year", "month", "day", "hour", "minute", "second", "nanosec‐
181           ond".  It also accepts "locale", "time_zone", and "formatter"
182           parameters.
183
184             my $dt = DateTime->new( year   => 1066,
185                                     month  => 10,
186                                     day    => 25,
187                                     hour   => 7,
188                                     minute => 15,
189                                     second => 47,
190                                     nanosecond => 500000000,
191                                     time_zone  => 'America/Chicago',
192                                   );
193
194           DateTime validates the "month", "day", "hour", "minute", and "sec‐
195           ond", and "nanosecond" parameters.  The valid values for these
196           parameters are:
197
198           * month 1-12
199
200           * day   1-31, and it must be within the valid range of days for the
201                   specified month
202
203           * hour  0-23
204
205           * minute
206                   0-59
207
208           * second
209                   0-61 (to allow for leap seconds).  Values of 60 or 61 are
210                   only allowed when they match actual leap seconds.
211
212           * nanosecond
213                   >= 0
214
215       Invalid parameter types (like an array reference) will cause the con‐
216       structor to die.
217
218       The value for seconds may be from 0 to 61, to account for leap seconds.
219       If you give a value greater than 59, DateTime does check to see that it
220       really matches a valid leap second.
221
222       All of the parameters are optional except for "year".  The "month" and
223       "day" parameters both default to 1, while the "hour", "minute", "sec‐
224       ond", and "nanosecond" parameters all default to 0.
225
226       The "locale" parameter should be a string matching one of the valid
227       locales, or a "DateTime::Locale" object.  See the DateTime::Locale doc‐
228       umentation for details.
229
230       The time_zone parameter can be either a scalar or a "DateTime::Time‐
231       Zone" object.  A string will simply be passed to the "DateTime::Time‐
232       Zone->new" method as its "name" parameter.  This string may be an Olson
233       DB time zone name ("America/Chicago"), an offset string ("+0630"), or
234       the words "floating" or "local".  See the "DateTime::TimeZone" documen‐
235       tation for more details.
236
237       The default time zone is "floating".
238
239       The "formatter" can be either a scalar or an object, but the class
240       specified by the scalar or the object must implement a "format_date‐
241       time()" method.
242
243       Ambiguous Local Times
244
245       Because of Daylight Saving Time, it is possible to specify a local time
246       that is ambiguous.  For example, in the US in 2003, the transition from
247       to saving to standard time occurred on October 26, at 02:00:00 local
248       time.  The local clock changed from 01:59:59 (saving time) to 01:00:00
249       (standard time).  This means that the hour from 01:00:00 through
250       01:59:59 actually occurs twice, though the UTC time continues to move
251       forward.
252
253       If you specify an ambiguous time, then the latest UTC time is always
254       used, in effect always choosing standard time.  In this case, you can
255       simply subtract an hour to the object in order to move to saving time,
256       for example:
257
258         # This object represent 01:30:00 standard time
259         my $dt = DateTime->new( year   => 2003,
260                                 month  => 10,
261                                 day    => 26,
262                                 hour   => 1,
263                                 minute => 30,
264                                 second => 0,
265                                 time_zone => 'America/Chicago',
266                               );
267
268         print $dt->hms;  # prints 01:30:00
269
270         # Now the object represent 01:30:00 saving time
271         $dt->subtract( hours => 1 );
272
273         print $dt->hms;  # still prints 01:30:00
274
275       Alternately, you could create the object with the UTC time zone, and
276       then call the "set_time_zone()" method to change the time zone.  This
277       is a good way to ensure that the time is not ambiguous.
278
279       Invalid Local Times
280
281       Another problem introduced by Daylight Saving Time is that certain
282       local times just do not exist.  For example, in the US in 2003, the
283       transition from standard to saving time occurred on April 6, at the
284       change to 2:00:00 local time.  The local clock changes from 01:59:59
285       (standard time) to 03:00:00 (saving time).  This means that there is no
286       02:00:00 through 02:59:59 on April 6!
287
288       Attempting to create an invalid time currently causes a fatal error.
289       This may change in future version of this module.
290
291       * from_epoch( epoch => $epoch, ... )
292           This class method can be used to construct a new DateTime object
293           from an epoch time instead of components.  Just as with the "new()"
294           method, it accepts "time_zone", "locale", and "formatter" parame‐
295           ters.
296
297           If the epoch value is not an integer, the part after the decimal
298           will be converted to nanoseconds.  This is done in order to be com‐
299           patible with "Time::HiRes".  If the floating portion extends past 9
300           decimal places, it will be truncated to nine, so that 1.1234567891
301           will become 1 second and 123,456,789 nanoseconds.
302
303           By default, the returned object will be in the UTC time zone.
304
305       * now( ... )
306           This class method is equivalent to calling "from_epoch()" with the
307           value returned from Perl's "time()" function.  Just as with the
308           "new()" method, it accepts "time_zone" and "locale" parameters.
309
310           By default, the returned object will be in the UTC time zone.
311
312       * today( ... )
313           This class method is equivalent to:
314
315             DateTime->now->truncate( to => 'day' );
316
317       * from_object( object => $object, ... )
318           This class method can be used to construct a new DateTime object
319           from any object that implements the "utc_rd_values()" method.  All
320           "DateTime::Calendar" modules must implement this method in order to
321           provide cross-calendar compatibility.  This method accepts a
322           "locale" and "formatter" parameter
323
324           If the object passed to this method has a "time_zone()" method,
325           that is used to set the time zone of the newly created "Date‐
326           Time.pm" object.
327
328           Otherwise, the returned object will be in the floating time zone.
329
330       * last_day_of_month( ... )
331           This constructor takes the same arguments as can be given to the
332           "new()" method, except for "day".  Additionally, both "year" and
333           "month" are required.
334
335       * from_day_of_year( ... )
336           This constructor takes the same arguments as can be given to the
337           "new()" method, except that it does not accept a "month" or "day"
338           argument.  Instead, it requires both "year" and "day_of_year".  The
339           day of year must be between 1 and 366, and 366 is only allowed for
340           leap years.
341
342       * clone
343           This object method returns a new object that is replica of the
344           object upon which the method is called.
345
346       "Get" Methods
347
348       This class has many methods for retrieving information about an object.
349
350       * year
351           Returns the year.
352
353       * ce_year
354           Returns the year according to the BCE/CE numbering system.  The
355           year before year 1 in this system is year -1, aka "1 BCE".
356
357       * era_name
358           Returns the long name of the current era, something like "Before
359           Christ".  See the Locales section for more details.
360
361       * era_abbr
362           Returns the abbreviated name of the current era, something like
363           "BC".  See the Locales section for more details.
364
365       * christian_era
366           Returns a string, either "BC" or "AD", according to the year.
367
368       * secular_era
369           Returns a string, either "BCE" or "CE", according to the year.
370
371       * year_with_era
372           Returns a string containing the year immediately followed by its
373           era abbreviation.  The year is the absolute value of "ce_year()",
374           so that year 1 is "1BC" and year 0 is "1AD".
375
376       * year_with_christian_era
377           Like "year_with_era()", but uses the christian_era() to get the era
378           name.
379
380       * year_with_secular_era
381           Like "year_with_era()", but uses the secular_era() method to get
382           the era name.
383
384       * month, mon
385           Returns the month of the year, from 1..12.
386
387       * month_name
388           Returns the name of the current month.  See the Locales section for
389           more details.
390
391       * month_abbr
392           Returns the abbreviated name of the current month.  See the Locales
393           section for more details.
394
395       * day_of_month, day, mday
396           Returns the day of the month, from 1..31.
397
398       * day_of_week, wday, dow
399           Returns the day of the week as a number, from 1..7, with 1 being
400           Monday and 7 being Sunday.
401
402       * day_name
403           Returns the name of the current day of the week.  See the Locales
404           section for more details.
405
406       * day_abbr
407           Returns the abbreviated name of the current day of the week.  See
408           the Locales section for more details.
409
410       * day_of_year, doy
411           Returns the day of the year.
412
413       * quarter
414           Returns the quarter of the year, from 1..4.
415
416       * quarter_name
417           Returns the name of the current quarter.  See the Locales section
418           for more details.
419
420       * quarter_abbr
421           Returns the abbreviated name of the current quarter.  See the
422           Locales section for more details.
423
424       * day_of_quarter, doq
425           Returns the day of the quarter.
426
427       * weekday_of_month
428           Returns a number from 1..5 indicating which week day of the month
429           this is.  For example, June 9, 2003 is the second Monday of the
430           month, and so this method returns 2 for that day.
431
432       * ymd( $optional_separator ), date
433       * mdy( $optional_separator )
434       * dmy( $optional_separator )
435           Each method returns the year, month, and day, in the order indi‐
436           cated by the method name.  Years are zero-padded to four digits.
437           Months and days are 0-padded to two digits.
438
439           By default, the values are separated by a dash (-), but this can be
440           overridden by passing a value to the method.
441
442       * hour
443           Returns the hour of the day, from 0..23.
444
445       * hour_1
446           Returns the hour of the day, from 1..24.
447
448       * hour_12
449           Returns the hour of the day, from 1..12.
450
451       * hour_12_0
452           Returns the hour of the day, from 0..11.
453
454       * minute, min
455           Returns the minute of the hour, from 0..59.
456
457       * second, sec
458           Returns the second, from 0..61.  The values 60 and 61 are used for
459           leap seconds.
460
461       * fractional_second
462           Returns the second, as a real number from 0.0 until 61.999999999
463
464           The values 60 and 61 are used for leap seconds.
465
466       * millisecond
467           Returns the fractional part of the second as milliseconds (1E-3
468           seconds).
469
470           Half a second is 500 milliseconds.
471
472       * microsecond
473           Returns the fractional part of the second as microseconds (1E-6
474           seconds).  This value will be rounded to an integer.
475
476           Half a second is 500_000 microseconds.  This value will be rounded
477           to an integer.
478
479       * nanosecond
480           Returns the fractional part of the second as nanoseconds (1E-9 sec‐
481           onds).
482
483           Half a second is 500_000_000 nanoseconds.
484
485       * hms( $optional_separator ), time
486           Returns the hour, minute, and second, all zero-padded to two dig‐
487           its.  If no separator is specified, a colon (:) is used by default.
488
489       * datetime, iso8601
490           This method is equivalent to:
491
492             $dt->ymd('-') . 'T' . $dt->hms(':')
493
494       * is_leap_year
495           This method returns a true or false indicating whether or not the
496           datetime object is in a leap year.
497
498       * week
499            ($week_year, $week_number) = $dt->week;
500
501           Returns information about the calendar week which contains this
502           datetime object. The values returned by this method are also avail‐
503           able separately through the week_year and week_number methods.
504
505           The first week of the year is defined by ISO as the one which con‐
506           tains the fourth day of January, which is equivalent to saying that
507           it's the first week to overlap the new year by at least four days.
508
509           Typically the week year will be the same as the year that the
510           object is in, but dates at the very beginning of a calendar year
511           often end up in the last week of the prior year, and similarly, the
512           final few days of the year may be placed in the first week of the
513           next year.
514
515       * week_year
516           Returns the year of the week.
517
518       * week_number
519           Returns the week of the year, from 1..53.
520
521       * week_of_month
522           The week of the month, from 0..5.  The first week of the month is
523           the first week that contains a Thursday.  This is based on the ICU
524           definition of week of month, and correlates to the ISO8601 week of
525           year definition.  A day in the week before the week with the first
526           Thursday will be week 0.
527
528       * jd, mjd
529           These return the Julian Day and Modified Julian Day, respectively.
530           The value returned is a floating point number.  The fractional por‐
531           tion of the number represents the time portion of the datetime.
532
533       * time_zone
534           This returns the "DateTime::TimeZone" object for the datetime
535           object.
536
537       * offset
538           This returns the offset from UTC, in seconds, of the datetime
539           object according to the time zone.
540
541       * is_dst
542           Returns a boolean indicating whether or not the datetime object is
543           currently in Daylight Saving Time or not.
544
545       * time_zone_long_name
546           This is a shortcut for "$dt->time_zone->name".  It's provided so
547           that one can use "%{time_zone_long_name}" as a strftime format
548           specifier.
549
550       * time_zone_short_name
551           This method returns the time zone abbreviation for the current time
552           zone, such as "PST" or "GMT".  These names are not definitive, and
553           should not be used in any application intended for general use by
554           users around the world.
555
556       * strftime( $format, ... )
557           This method implements functionality similar to the "strftime()"
558           method in C.  However, if given multiple format strings, then it
559           will return multiple scalars, one for each format string.
560
561           See the strftime Specifiers section for a list of all possible for‐
562           mat specifiers.
563
564           If you give a format specifier that doesn't exist, then it is sim‐
565           ply treated as text.
566
567       * epoch
568           Return the UTC epoch value for the datetime object.  Internally,
569           this is implemented using "Time::Local", which uses the Unix epoch
570           even on machines with a different epoch (such as MacOS).  Datetimes
571           before the start of the epoch will be returned as a negative num‐
572           ber.
573
574           This return value from this method is always an integer.
575
576           Since the epoch does not account for leap seconds, the epoch time
577           for 1972-12-31T23:59:60 (UTC) is exactly the same as that for
578           1973-01-01T00:00:00.
579
580           Epoch times cannot represent many dates on most platforms, and this
581           method may simply return undef in some cases.
582
583           Using your system's epoch time may be error-prone, since epoch
584           times have such a limited range on 32-bit machines.  Additionally,
585           the fact that different operating systems have different epoch
586           beginnings is another source of possible bugs.
587
588       * hires_epoch
589           Returns the epoch as a floating point number.  The floating point
590           portion of the value represents the nanosecond value of the object.
591           This method is provided for compatibility with the "Time::HiRes"
592           module.
593
594       * is_finite, is_infinite
595           These methods allow you to distinguish normal datetime objects from
596           infinite ones.  Infinite datetime objects are documented in Date‐
597           Time::Infinite.
598
599       * utc_rd_values
600           Returns the current UTC Rata Die days, seconds, and nanoseconds as
601           a three element list.  This exists primarily to allow other calen‐
602           dar modules to create objects based on the values provided by this
603           object.
604
605       * local_rd_values
606           Returns the current local Rata Die days, seconds, and nanoseconds
607           as a three element list.  This exists for the benefit of other mod‐
608           ules which might want to use this information for date math, such
609           as "DateTime::Event::Recurrence".
610
611       * leap_seconds
612           Returns the number of leap seconds that have happened up to the
613           datetime represented by the object.  For floating datetimes, this
614           always returns 0.
615
616       * utc_rd_as_seconds
617           Returns the current UTC Rata Die days and seconds purely as sec‐
618           onds.  This number ignores any fractional seconds stored in the
619           object, as well as leap seconds.
620
621       * local_rd_as_seconds - deprecated
622           Returns the current local Rata Die days and seconds purely as sec‐
623           onds.  This number ignores any fractional seconds stored in the
624           object, as well as leap seconds.
625
626       * locale
627           Returns the current locale object.
628
629       * formatter
630           Returns current formatter object or class. See "Formatters And
631           Stringification" for details.
632
633       "Set" Methods
634
635       The remaining methods provided by "DateTime.pm", except where otherwise
636       specified, return the object itself, thus making method chaining possi‐
637       ble. For example:
638
639         my $dt = DateTime->now->set_time_zone( 'Australia/Sydney' );
640
641         my $first = DateTime
642                       ->last_day_of_month( year => 2003, month => 3 )
643                       ->add( days => 1 )
644                       ->subtract( seconds => 1 );
645
646       * set( .. )
647           This method can be used to change the local components of a date
648           time, or its locale.  This method accepts any parameter allowed by
649           the "new()" method except for "time_zone".  Time zones may be set
650           using the "set_time_zone()" method.
651
652           This method performs parameters validation just as is done in the
653           "new()" method.
654
655       * set_year(), set_month(), set_day(), set_hour(), set_minute(),
656       set_second(), set_nanosecond(), set_locale()
657           These are shortcuts to calling "set()" with a single key.  They all
658           take a single parameter.
659
660       * truncate( to => ... )
661           This method allows you to reset some of the local time components
662           in the object to their "zero" values.  The "to" parameter is used
663           to specify which values to truncate, and it may be one of "year",
664           "month", "week", "day", "hour", "minute", or "second".  For exam‐
665           ple, if "month" is specified, then the local day becomes 1, and the
666           hour, minute, and second all become 0.
667
668           If "week" is given, then the datetime is set to the beginning of
669           the week in which it occurs, and the time components are all set to
670           0.
671
672       * set_time_zone( $tz )
673           This method accepts either a time zone object or a string that can
674           be passed as the "name" parameter to "DateTime::TimeZone->new()".
675           If the new time zone's offset is different from the old time zone,
676           then the local time is adjusted accordingly.
677
678           For example:
679
680             my $dt = DateTime->new( year => 2000, month => 5, day => 10,
681                                     hour => 15, minute => 15,
682                                     time_zone => 'America/Los_Angeles', );
683
684             print $dt->hour; # prints 15
685
686             $dt->set_time_zone( 'America/Chicago' );
687
688             print $dt->hour; # prints 17
689
690           If the old time zone was a floating time zone, then no adjustments
691           to the local time are made, except to account for leap seconds.  If
692           the new time zone is floating, then the UTC time is adjusted in
693           order to leave the local time untouched.
694
695           Fans of Tsai Ming-Liang's films will be happy to know that this
696           does work:
697
698             my $dt = DateTime->now( time_zone => 'Asia/Taipei' );
699
700             $dt->set_time_zone( 'Europe/Paris' );
701
702           Yes, now we can know "ni3 na4 bian1 ji2dian3?"
703
704       * set_formatter( $formatter )
705           Set the formatter for the object. See "Formatters And Stringifica‐
706           tion" for details.
707
708       * add_duration( $duration_object )
709           This method adds a "DateTime::Duration" to the current datetime.
710           See the DateTime::Duration docs for more details.
711
712       * add( DateTime::Duration->new parameters )
713           This method is syntactic sugar around the "add_duration()" method.
714           It simply creates a new "DateTime::Duration" object using the
715           parameters given, and then calls the "add_duration()" method.
716
717       * subtract_duration( $duration_object )
718           When given a "DateTime::Duration" object, this method simply calls
719           "invert()" on that object and passes that new duration to the
720           "add_duration" method.
721
722       * subtract( DateTime::Duration->new parameters )
723           Like "add()", this is syntactic sugar for the "subtract_duration()"
724           method.
725
726       * subtract_datetime( $datetime )
727           This method returns a new "DateTime::Duration" object representing
728           the difference between the two dates.  The duration is relative to
729           the object from which $datetime is subtracted.  For example:
730
731               2003-03-15 00:00:00.00000000
732            -  2003-02-15 00:00:00.00000000
733
734            -------------------------------
735
736            = 1 month
737
738           Note that this duration is not an absolute measure of the amount of
739           time between the two datetimes, because the length of a month
740           varies,, as well as due to the presence of leap seconds.
741
742           The returned duration may have deltas for months, days, minutes,
743           seconds, and nanoseconds.
744
745       * delta_md( $datetime )
746       * delta_days( $datetime )
747           Each of these methods returns a new "DateTime::Duration" object
748           representing some portion of the difference between two datetimes.
749           The "delta_md()" method returns a duration which contains only the
750           month and day portions of the duration is represented.  The
751           "delta_days()" method returns a duration which contains only days.
752
753           The "delta_md" and "delta_days" methods truncate the duration so
754           that any fractional portion of a day is ignored.  Both of these
755           methods operate on the date portion of a datetime only, and so
756           effectively ignore the time zone.
757
758           Unlike the subtraction methods, these methods always return a posi‐
759           tive (or zero) duration.
760
761       * delta_ms( $datetime )
762           Returns a duration which contains only minutes and seconds.  Any
763           day and month differences to minutes are converted to minutes and
764           seconds.
765
766           Always return a positive (or zero) duration.
767
768       * subtract_datetime_absolute( $datetime )
769           This method returns a new "DateTime::Duration" object representing
770           the difference between the two dates in seconds and nanoseconds.
771           This is the only way to accurately measure the absolute amount of
772           time between two datetimes, since units larger than a second do not
773           represent a fixed number of seconds.
774
775       Class Methods
776
777       * DefaultLocale( $locale )
778           This can be used to specify the default locale to be used when cre‐
779           ating DateTime objects.  If unset, then "en_US" is used.
780
781       * compare
782       * compare_ignore_floating
783             $cmp = DateTime->compare( $dt1, $dt2 );
784
785             $cmp = DateTime->compare_ignore_floating( $dt1, $dt2 );
786
787           Compare two DateTime objects.  The semantics are compatible with
788           Perl's "sort()" function; it returns -1 if $a < $b, 0 if $a == $b,
789           1 if $a > $b.
790
791           If one of the two DateTime objects has a floating time zone, it
792           will first be converted to the time zone of the other object.  This
793           is what you want most of the time, but it can lead to inconsistent
794           results when you compare a number of DateTime objects, some of
795           which are floating, and some of which are in other time zones.
796
797           If you want to have consistent results (because you want to sort a
798           number of objects, for example), you can use the "com‐
799           pare_ignore_floating()" method:
800
801             @dates = sort { DateTime->compare_ignore_floating($a, $b) } @dates;
802
803           In this case, objects with a floating time zone will be sorted as
804           if they were UTC times.
805
806           Since DateTime objects overload comparison operators, this:
807
808             @dates = sort @dates;
809
810           is equivalent to this:
811
812             @dates = sort { DateTime->compare($a, $b) } @dates;
813
814           DateTime objects can be compared to any other calendar class that
815           implements the "utc_rd_values()" method.
816
817       How Datetime Math is Done
818
819       It's important to have some understanding of how datetime math is
820       implemented in order to effectively use this module and "Date‐
821       Time::Duration".
822
823       Making Things Simple
824
825       If you want to simplify your life and not have to think too hard about
826       the nitty-gritty of datetime math, I have several recommendations:
827
828       * use the floating time zone
829           If you do not care about time zones or leap seconds, use the
830           "floating" timezone:
831
832             my $dt = DateTime->now( time_zone => 'floating' );
833
834           Math done on two objects in the floating time zone produces very
835           predictable results.
836
837       * use UTC for all calculations
838           If you do care about time zones (particularly DST) or leap seconds,
839           try to use non-UTC time zones for presentation and user input only.
840           Convert to UTC immediately and convert back to the local time zone
841           for presentation:
842
843             my $dt = DateTime->new( %user_input, time_zone => $user_tz );
844             $dt->set_time_zone('UTC');
845
846             # do various operations - store it, retrieve it, add, subtract, etc.
847
848             $dt->set_time_zone($user_tz);
849             print $dt->datetime;
850
851       * math on non-UTC time zones
852           If you need to do date math on objects with non-UTC time zones,
853           please read the caveats below carefully.  The results "DateTime.pm"
854           are predictable and correct, and mostly intuitive, but datetime
855           math gets very ugly when time zones are involved, and there are a
856           few strange corner cases involving subtraction of two datetimes
857           across a DST change.
858
859           If you can always use the floating or UTC time zones, you can skip
860           ahead to Leap Seconds and Date Math
861
862       * date vs datetime math
863           If you only care about the date (calendar) portion of a datetime,
864           you should use either "delta_md()" or "delta_days()", not "sub‐
865           tract_datetime()".  This will give predictable, unsurprising
866           results, free from DST-related complications.
867
868       * subtract_datetime() and add_duration()
869           You must convert your datetime objects to the UTC time zone before
870           doing date math if you want to make sure that the following formu‐
871           las are always true:
872
873             $dt2 - $dt1 = $dur
874             $dt1 + $dur = $dt2
875             $dt2 - $dur = $dt1
876
877           Note that using "delta_days" ensures that this formula always
878           works, regardless of the timezone of the objects involved, as does
879           using "subtract_datetime_absolute()".  Anything may sometimes be
880           non-reversible.
881
882       Adding a Duration to a Datetime
883
884       The parts of a duration can be broken down into five parts.  These are
885       months, days, minutes, seconds, and nanoseconds.  Adding one month to a
886       date is different than adding 4 weeks or 28, 29, 30, or 31 days.  Simi‐
887       larly, due to DST and leap seconds, adding a day can be different than
888       adding 86,400 seconds, and adding a minute is not exactly the same as
889       60 seconds.
890
891       We cannot convert between these units, except for seconds and nanosec‐
892       onds, because there is no fixed conversion between the two units,
893       because of things like leap seconds, DST changes, etc.
894
895       "DateTime.pm" always adds (or subtracts) days, then months, minutes,
896       and then seconds and nanoseconds.  If there are any boundary overflows,
897       these are normalized at each step.  For the days and months (the calen‐
898       dar) the local (not UTC) values are used.  For minutes and seconds, the
899       local values are used.  This generally just works.
900
901       This means that adding one month and one day to February 28, 2003 will
902       produce the date April 1, 2003, not March 29, 2003.
903
904         my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
905
906         $dt->add( months => 1, days => 1 );
907
908         # 2003-04-01 - the result
909
910       On the other hand, if we add months first, and then separately add
911       days, we end up with March 29, 2003:
912
913         $dt->add( months => 1 )->add( days => 1 );
914
915         # 2003-03-29
916
917       We see similar strangeness when math crosses a DST boundary:
918
919         my $dt = DateTime->new( year => 2003, month => 4, day => 5,
920                                 hour => 1, minute => 58,
921                                 time_zone => "America/Chicago",
922                               );
923
924         $dt->add( days => 1, minutes => 3 );
925         # 2003-04-06 02:01:00
926
927         $dt->add( minutes => 3 )->( days => 1 );
928         # 2003-04-06 03:01:00
929
930       Note that if you converted the datetime object to UTC first you would
931       get predictable results.
932
933       If you want to know how many seconds a duration object represents, you
934       have to add it to a datetime to find out, so you could do:
935
936        my $now = DateTime->now( time_zone => 'UTC' );
937        my $later = $now->clone->add_duration($duration);
938
939        my $seconds_dur = $later->subtract_datetime_absolute($now);
940
941       This returns a duration which only contains seconds and nanoseconds.
942
943       If we were add the duration to a different datetime object we might get
944       a different number of seconds.
945
946       If you need to do lots of work with durations, take a look at Rick
947       Measham's "DateTime::Format::Duration" module, which lets you present
948       information from durations in many useful ways.
949
950       There are other subtract/delta methods in DateTime.pm to generate dif‐
951       ferent types of durations.  These methods are "subtract_datetime()",
952       "subtract_datetime_absolute()", "delta_md()", "delta_days()", and
953       "delta_ms()".
954
955       Datetime Subtraction
956
957       Date subtraction is done solely based on the two object's local date‐
958       times, with one exception to handle DST changes.  Also, if the two
959       datetime objects are in different time zones, one of them is converted
960       to the other's time zone first before subtraction.  This is best
961       explained through examples:
962
963       The first of these probably makes the most sense:
964
965           my $dt1 = DateTime->new( year => 2003, month => 5, day => 6,
966                                    time_zone => 'America/Chicago',
967                                  );
968           # not DST
969
970           my $dt2 = DateTime->new( year => 2003, month => 11, day => 6,
971                                    time_zone => 'America/Chicago',
972                                  );
973           # is DST
974
975           my $dur = $dt2->subtract_datetime($dt1);
976           # 6 months
977
978       Nice and simple.
979
980       This one is a little trickier, but still fairly logical:
981
982           my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
983                                    hour => 1, minute => 58,
984                                    time_zone => "America/Chicago",
985                                  );
986           # is DST
987
988           my $dt2 = DateTime->new( year => 2003, month => 4, day => 7,
989                                    hour => 2, minute => 1,
990                                    time_zone => "America/Chicago",
991                                  );
992           # not DST
993
994           my $dur = $dt2->subtract_datetime($dt1);
995           # 2 days and 3 minutes
996
997       Which contradicts the result this one gives, even though they both make
998       sense:
999
1000           my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
1001                                    hour => 1, minute => 58,
1002                                    time_zone => "America/Chicago",
1003                                  );
1004           # is DST
1005
1006           my $dt2 = DateTime->new( year => 2003, month => 4, day => 6,
1007                                    hour => 3, minute => 1,
1008                                    time_zone => "America/Chicago",
1009                                  );
1010           # not DST
1011
1012           my $dur = $dt2->subtract_datetime($dt1);
1013           # 1 day and 3 minutes
1014
1015       This last example illustrates the "DST" exception mentioned earlier.
1016       The exception accounts for the fact 2003-04-06 only lasts 23 hours.
1017
1018       And finally:
1019
1020           my $dt2 = DateTime->new( year => 2003, month => 10, day => 26,
1021                                    hour => 1,
1022                                    time_zone => 'America/Chicago',
1023                                  );
1024
1025           my $dt1 = $dt2->clone->subtract( hours => 1 );
1026
1027           my $dur = $dt2->subtract_datetime($dt1);
1028           # 60 minutes
1029
1030       This seems obvious until you realize that subtracting 60 minutes from
1031       $dt2 in the above example still leaves the clock time at "01:00:00".
1032       This time we are accounting for a 25 hour day.
1033
1034       Reversibility
1035
1036       Date math operations are not always reversible.  This is because of the
1037       way that addition operations are ordered.  As was discussed earlier,
1038       adding 1 day and 3 minutes in one call to "add()" is not the same as
1039       first adding 3 minutes and 1 day in two separate calls.
1040
1041       If we take a duration returned from "subtract_datetime()" and then try
1042       to add or subtract that duration from one of the datetimes we just
1043       used, we sometimes get interesting results:
1044
1045         my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
1046                                  hour => 1, minute => 58,
1047                                  time_zone => "America/Chicago",
1048                                );
1049
1050         my $dt2 = DateTime->new( year => 2003, month => 4, day => 6,
1051                                  hour => 3, minute => 1,
1052                                  time_zone => "America/Chicago",
1053                                );
1054
1055         my $dur = $dt2->subtract_datetime($dt1);
1056         # 1 day and 3 minutes
1057
1058         $dt1->add_duration($dur);
1059         # gives us $dt2
1060
1061         $dt2->subtract_duration($dur);
1062         # gives us 2003-04-05 02:58:00 - 1 hour later than $dt1
1063
1064       The "subtract_dauration()" operation gives us a (perhaps) unexpected
1065       answer because it first subtracts one day to get 2003-04-05T03:01:00
1066       and then subtracts 3 minutes to get the final result.
1067
1068       If we explicitly reverse the order we can get the original value of
1069       $dt1. This can be facilitated by "DateTime::Duration"'s "calendar_dura‐
1070       tion()" and "clock_duration()" methods:
1071
1072         $dt2->subtract_duration( $dur->clock_duration )
1073             ->subtract_duration( $dur->calendar_duration );
1074
1075       Leap Seconds and Date Math
1076
1077       The presence of leap seconds can cause even more anomalies in date
1078       math.  For example, the following is a legal datetime:
1079
1080         my $dt = DateTime->new( year => 1972, month => 12, day => 31,
1081                                 hour => 23, minute => 59, second => 60,
1082                                 time_zone => 'UTC' );
1083
1084       If we do the following:
1085
1086        $dt->add( months => 1 );
1087
1088       Then the datetime is now "1973-02-01 00:00:00", because there is no
1089       23:59:60 on 1973-01-31.
1090
1091       Leap seconds also force us to distinguish between minutes and seconds
1092       during date math.  Given the following datetime:
1093
1094         my $dt = DateTime->new( year => 1972, month => 12, day => 31,
1095                                 hour => 23, minute => 59, second => 30,
1096                                 time_zone => 'UTC' );
1097
1098       we will get different results when adding 1 minute than we get if we
1099       add 60 seconds.  This is because in this case, the last minute of the
1100       day, beginning at 23:59:00, actually contains 61 seconds.
1101
1102       Here are the results we get:
1103
1104         # 1972-12-31 23:59:30 - our starting datetime
1105
1106         $dt->clone->add( minutes => 1 );
1107         # 1973-01-01 00:00:30 - one minute later
1108
1109         $dt->clone->add( seconds => 60 );
1110         # 1973-01-01 00:00:29 - 60 seconds later
1111
1112         $dt->clone->add( seconds => 61 );
1113         # 1973-01-01 00:00:30 - 61 seconds later
1114
1115       Local vs. UTC and 24 hours vs. 1 day
1116
1117       When math crosses a daylight saving boundary, a single day may have
1118       more or less than 24 hours.
1119
1120       For example, if you do this:
1121
1122         my $dt = DateTime->new( year => 2003, month => 4, day => 5,
1123                                 hour => 2,
1124                                 time_zone => 'America/Chicago',
1125                               );
1126         $dt->add( days => 1 );
1127
1128       then you will produce an invalid local time, and therefore an exception
1129       will be thrown.
1130
1131       However, this works:
1132
1133         my $dt = DateTime->new( year => 2003, month => 4, day => 5,
1134                                 hour => 2,
1135                                 time_zone => 'America/Chicago',
1136                               );
1137         $dt->add( hours => 24 );
1138
1139       and produces a datetime with the local time of "03:00".
1140
1141       If all this makes your head hurt, there is a simple alternative.  Just
1142       convert your datetime object to the "UTC" time zone before doing date
1143       math on it, and switch it back to the local time zone afterwards.  This
1144       avoids the possibility of having date math throw an exception, and
1145       makes sure that 1 day equals 24 hours.  Of course, this may not always
1146       be desirable, so caveat user!
1147
1148       Overloading
1149
1150       This module explicitly overloads the addition (+), subtraction (-),
1151       string and numeric comparison operators.  This means that the following
1152       all do sensible things:
1153
1154         my $new_dt = $dt + $duration_obj;
1155
1156         my $new_dt = $dt - $duration_obj;
1157
1158         my $duration_obj = $dt - $new_dt;
1159
1160         foreach my $dt ( sort @dts ) { ... }
1161
1162       Additionally, the fallback parameter is set to true, so other derivable
1163       operators (+=, -=, etc.) will work properly.  Do not expect increment
1164       (++) or decrement (--) to do anything useful.
1165
1166       The module also overloads stringification to use the "iso8601()"
1167       method.
1168
1169       Formatters And Stringification
1170
1171       You can optionally specify a "formatter", which is usually a Date‐
1172       Time::Format::* object/class, to control how the stringification of the
1173       DateTime object.
1174
1175       Any of the constructor methods can accept a formatter argument:
1176
1177         my $formatter = DateTime::Format::Strptime->new(...);
1178         my $dt = DateTime->new(year => 2004, formatter => $formatter);
1179
1180       Or, you can set it afterwards:
1181
1182         $dt->set_formatter($formatter);
1183         $formatter = $dt->formatter();
1184
1185       Once you set the formatter, the overloaded stringification method will
1186       use the formatter. If unspecified, the "iso8601()" method is used.
1187
1188       A formatter can be handy when you know that in your application you
1189       want to stringify your DateTime objects into a special format all the
1190       time, for example to a different language.
1191
1192       strftime Specifiers
1193
1194       The following specifiers are allowed in the format string given to the
1195       "strftime()" method:
1196
1197       * %a
1198           The abbreviated weekday name.
1199
1200       * %A
1201           The full weekday name.
1202
1203       * %b
1204           The abbreviated month name.
1205
1206       * %B
1207           The full month name.
1208
1209       * %c
1210           The default datetime format for the object's locale.
1211
1212       * %C
1213           The century number (year/100) as a 2-digit integer.
1214
1215       * %d
1216           The day of the month as a decimal number (range 01 to 31).
1217
1218       * %D
1219           Equivalent to %m/%d/%y.  This is not a good standard format if you
1220           want folks from both the United States and the rest of the world to
1221           understand the date!
1222
1223       * %e
1224           Like %d, the day of the month as a decimal number, but a leading
1225           zero is replaced by a space.
1226
1227       * %F
1228           Equivalent to %Y-%m-%d (the ISO 8601 date format)
1229
1230       * %G
1231           The ISO 8601 year with century as a decimal number.  The 4-digit
1232           year corresponding to the ISO week number (see %V).  This has the
1233           same format and value as %Y, except that if the ISO week number
1234           belongs to the previous or next year, that year is used instead.
1235           (TZ)
1236
1237       * %g
1238           Like %G, but without century, i.e., with a 2-digit year (00-99).
1239
1240       * %h
1241           Equivalent to %b.
1242
1243       * %H
1244           The hour as a decimal number using a 24-hour clock (range 00 to
1245           23).
1246
1247       * %I
1248           The hour as a decimal number using a 12-hour clock (range 01 to
1249           12).
1250
1251       * %j
1252           The day of the year as a decimal number (range 001 to 366).
1253
1254       * %k
1255           The hour (24-hour clock) as a decimal number (range 0 to 23); sin‐
1256           gle digits are preceded by a blank. (See also %H.)
1257
1258       * %l
1259           The hour (12-hour clock) as a decimal number (range 1 to 12); sin‐
1260           gle digits are preceded by a blank. (See also %I.)
1261
1262       * %m
1263           The month as a decimal number (range 01 to 12).
1264
1265       * %M
1266           The minute as a decimal number (range 00 to 59).
1267
1268       * %n
1269           A newline character.
1270
1271       * %N
1272           The fractional seconds digits. Default is 9 digits (nanoseconds).
1273
1274             %3N   milliseconds (3 digits)
1275             %6N   microseconds (6 digits)
1276             %9N   nanoseconds  (9 digits)
1277
1278       * %p
1279           Either `AM' or `PM' according to the given time value, or the cor‐
1280           responding strings for the current locale.  Noon is treated as `pm'
1281           and midnight as `am'.
1282
1283       * %P
1284           Like %p but in lowercase: `am' or `pm' or a corresponding string
1285           for the current locale.
1286
1287       * %r
1288           The time in a.m.  or p.m. notation.  In the POSIX locale this is
1289           equivalent to `%I:%M:%S %p'.
1290
1291       * %R
1292           The time in 24-hour notation (%H:%M). (SU) For a version including
1293           the seconds, see %T below.
1294
1295       * %s
1296           The number of seconds since the epoch.
1297
1298       * %S
1299           The second as a decimal number (range 00 to 61).
1300
1301       * %t
1302           A tab character.
1303
1304       * %T
1305           The time in 24-hour notation (%H:%M:%S).
1306
1307       * %u
1308           The day of the week as a decimal, range 1 to 7, Monday being 1.
1309           See also %w.
1310
1311       * %U
1312           The week number of the current year as a decimal number, range 00
1313           to 53, starting with the first Sunday as the first day of week 01.
1314           See also %V and %W.
1315
1316       * %V
1317           The ISO 8601:1988 week number of the current year as a decimal num‐
1318           ber, range 01 to 53, where week 1 is the first week that has at
1319           least 4 days in the current year, and with Monday as the first day
1320           of the week. See also %U and %W.
1321
1322       * %w
1323           The day of the week as a decimal, range 0 to 6, Sunday being 0.
1324           See also %u.
1325
1326       * %W
1327           The week number of the current year as a decimal number, range 00
1328           to 53, starting with the first Monday as the first day of week 01.
1329
1330       * %x
1331           The default date format for the object's locale.
1332
1333       * %X
1334           The default time format for the object's locale.
1335
1336       * %y
1337           The year as a decimal number without a century (range 00 to 99).
1338
1339       * %Y
1340           The year as a decimal number including the century.
1341
1342       * %z
1343           The time-zone as hour offset from UTC.  Required to emit
1344           RFC822-conformant dates (using "%a, %d %b %Y %H:%M:%S %z").
1345
1346       * %Z
1347           The time zone or name or abbreviation.
1348
1349       * %%
1350           A literal `%' character.
1351
1352       * %{method}
1353           Any method name may be specified using the format "%{method}" name
1354           where "method" is a valid "DateTime.pm" object method.
1355

DateTime.pm and Storable

1357       As of version 0.13, DateTime implements Storable hooks in order to
1358       reduce the size of a serialized DateTime object.
1359

KNOWN BUGS

1361       The tests in 20infinite.t seem to fail on some machines, particularly
1362       on Win32.  This appears to be related to Perl's internal handling of
1363       IEEE infinity and NaN, and seems to be highly platform/compiler/phase
1364       of moon dependent.
1365
1366       If you don't plan to use infinite datetimes you can probably ignore
1367       this.  This will be fixed (somehow) in future versions.
1368

SUPPORT

1370       Support for this module is provided via the datetime@perl.org email
1371       list.  See http://lists.perl.org/ for more details.
1372
1373       Please submit bugs to the CPAN RT system at
1374       http://rt.cpan.org/NoAuth/ReportBug.html?Queue=datetime or via email at
1375       bug-datetime@rt.cpan.org.
1376

AUTHOR

1378       Dave Rolsky <autarch@urth.org>
1379
1380       However, please see the CREDITS file for more details on who I really
1381       stole all the code from.
1382
1384       Copyright (c) 2003-2006 David Rolsky.  All rights reserved.  This pro‐
1385       gram is free software; you can redistribute it and/or modify it under
1386       the same terms as Perl itself.
1387
1388       Portions of the code in this distribution are derived from other works.
1389       Please see the CREDITS file for more details.
1390
1391       The full text of the license can be found in the LICENSE file included
1392       with this module.
1393

SEE ALSO

1395       datetime@perl.org mailing list
1396
1397       http://datetime.perl.org/
1398
1399
1400
1401perl v5.8.8                       2007-03-30                       DateTime(3)
Impressum