DateTime - A date and time object


NAME

DateTime - A date and time object


SYNOPSIS

  use DateTime;
  $dt = DateTime->new( year   => 1964,
                       month  => 10,
                       day    => 16,
                       hour   => 16,
                       minute => 12,
                       second => 47,
                       nanosecond => 500000000,
                       time_zone => 'Asia/Taipei',
                     );
  $dt = DateTime->from_epoch( epoch => $epoch );
  $dt = DateTime->now; # same as ( epoch => time() )
  $year   = $dt->year;
  $month  = $dt->month;          # 1-12 - also mon
  $day    = $dt->day;            # 1-31 - also day_of_month, mday
  $dow    = $dt->day_of_week;    # 1-7 (Monday is 1) - also dow, wday
  $hour   = $dt->hour;           # 0-23
  $minute = $dt->minute;         # 0-59 - also min
  $second = $dt->second;         # 0-61 (leap seconds!) - also sec
  $doy    = $dt->day_of_year;    # 1-366 (leap years) - also doy
  $doq    = $dt->day_of_quarter; # 1.. - also doq
  $qtr    = $dt->quarter;        # 1-4
  # all of the start-at-1 methods above have correponding start-at-0
  # methods, such as $dt->day_of_month_0, $dt->month_0 and so on
  $ymd    = $dt->ymd;           # 2002-12-06
  $ymd    = $dt->ymd('/');      # 2002/12/06 - also date
  $mdy    = $dt->mdy;           # 12-06-2002
  $mdy    = $dt->mdy('/');      # 12/06/2002
  $dmy    = $dt->dmy;           # 06-12-2002
  $dmy    = $dt->dmy('/');      # 06/12/2002
  $hms    = $dt->hms;           # 14:02:29
  $hms    = $dt->hms('!');      # 14!02!29 - also time
  $is_leap  = $dt->is_leap_year;
  # these are localizable, see Locales section
  $month_name  = $dt->month_name; # January, February, ...
  $month_abbr  = $dt->month_abbr; # Jan, Feb, ...
  $day_name    = $dt->day_name;   # Monday, Tuesday, ...
  $day_abbr    = $dt->day_abbr;   # Mon, Tue, ...
  $epoch_time  = $dt->epoch;
  # may return undef if the datetime is outside the range that is
  # representable by your OS's epoch system.
  $dt2 = $dt + $duration_object;
  $dt3 = $dt - $duration_object;
  $duration_object = $dt - $dt2;
  $dt->set( year => 1882 );
  $dt->set_time_zone( 'America/Chicago' );
  $dt->set_formatter( $formatter );


DESCRIPTION

DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project. For details on this project please see http://datetime.perl.org/. The DateTime site has a FAQ which may help answer many ``how do I do X?'' questions. The FAQ is at http://datetime.perl.org/faq.html.

It represents the Gregorian calendar, extended backwards in time before its creation (in 1582). This is sometimes known as the ``proleptic Gregorian calendar''. In this calendar, the first day of the calendar (the epoch), is the first day of year 1, which corresponds to the date which was (incorrectly) believed to be the birth of Jesus Christ.

The calendar represented does have a year 0, and in that way differs from how dates are often written using ``BCE/CE'' or ``BC/AD''.

For infinite datetimes, please see the DateTime::Infinite module.


USAGE

0-based Versus 1-based Numbers

The DateTime.pm module follows a simple consistent logic for determining whether or not a given number is 0-based or 1-based.

Month, day of month, day of week, and day of year are 1-based. Any method that is 1-based also has an equivalent 0-based method ending in ``_0''. So for example, this class provides both day_of_week() and day_of_week_0() methods.

The day_of_week_0() method still treats Monday as the first day of the week.

All time-related numbers such as hour, minute, and second are 0-based.

Years are neither, as they can be both positive or negative, unlike any other datetime component. There is a year 0.

There is no quarter_0() method.

Error Handling

Some errors may cause this module to die with an error string. This can only happen when calling constructor methods, methods that change the object, such as set(), or methods that take parameters. Methods that retrieve information about the object, such as year() or epoch(), will never die.

Locales

Some methods are localizable. This is done by setting the locale when constructing a DateTime object. There is also a DefaultLocale() class method which may be used to set the default locale for all DateTime objects created. If this is not set, then ``English'' is used.

Some locales may return data as Unicode. When using Perl 5.6.0 or greater, this will be a native Perl Unicode string. When using older Perls, this will be a sequence of bytes representing the Unicode character.

Floating DateTimes

The default time zone for new DateTime objects, except where stated otherwise, is the ``floating'' time zone. This concept comes from the iCal standard. A floating datetime is one which is not anchored to any particular time zone. In addition, floating datetimes do not include leap seconds, since we cannot apply them without knowing the datetime's time zone.

The results of date math and comparison between a floating datetime and one with a real time zone are not really valid, because one includes leap seconds and the other does not. Similarly, the results of datetime math between two floating datetimes and two datetimes with time zones are not really comparable.

If you are planning to use any objects with a real time zone, it is strongly recommended that you do not mix these with floating datetimes.

Methods

Constructors

All constructors can die when invalid parameters are given.

Invalid parameter types (like an array reference) will cause the constructor to die.

The value for seconds may be from 0 to 61, to account for leap seconds. If you give a value greater than 59, DateTime does check to see that it really matches a valid leap second.

All of the parameters are optional except for ``year''. The ``month'' and ``day'' parameters both default to 1, while the ``hour'', ``minute'', ``second'', and ``nanosecond'' parameters all default to 0.

The ``locale'' parameter should be a string matching one of the valid locales, or a DateTime::Locale object. See the DateTime::Locale documentation for details.

The time_zone parameter can be either a scalar or a DateTime::TimeZone object. A string will simply be passed to the DateTime::TimeZone->new method as its ``name'' parameter. This string may be an Olson DB time zone name (``America/Chicago''), an offset string (``+0630''), or the words ``floating'' or ``local''. See the DateTime::TimeZone documentation for more details.

The default time zone is ``floating''.

The ``formatter'' can be either a scalar or an object, but the class specified by the scalar or the object must implement a format_datetime() method.

Ambiguous Local Times

Because of Daylight Saving Time, it is possible to specify a local time that is ambiguous. For example, in the US in 2003, the transition from to saving to standard time occurred on October 26, at 02:00:00 local time. The local clock changed from 01:59:59 (saving time) to 01:00:00 (standard time). This means that the hour from 01:00:00 through 01:59:59 actually occurs twice, though the UTC time continues to move forward.

If you specify an ambiguous time, then the latest UTC time is always used, in effect always choosing standard time. In this case, you can simply subtract an hour to the object in order to move to saving time, for example:

  # This object represent 01:30:00 standard time
  my $dt = DateTime->new( year   => 2003,
                          month  => 10,
                          day    => 26,
                          hour   => 1,
                          minute => 30,
                          second => 0,
                          time_zone => 'America/Chicago',
                        );
  print $dt->hms;  # prints 01:30:00
  # Now the object represent 01:30:00 saving time
  $dt->subtract( hours => 1 );
  print $dt->hms;  # still prints 01:30:00

Alternately, you could create the object with the UTC time zone, and then call the set_time_zone() method to change the time zone. This is a good way to ensure that the time is not ambiguous.

Invalid Local Times

Another problem introduced by Daylight Saving Time is that certain local times just do not exist. For example, in the US in 2003, the transition from standard to saving time occurred on April 6, at the change to 2:00:00 local time. The local clock changes from 01:59:59 (standard time) to 03:00:00 (saving time). This means that there is no 02:00:00 through 02:59:59 on April 6!

Attempting to create an invalid time currently causes a fatal error. This may change in future version of this module.

``Get'' Methods

This class has many methods for retrieving information about an object.

``Set'' Methods

The remaining methods provided by DateTime.pm, except where otherwise specified, return the object itself, thus making method chaining possible. For example:

  my $dt = DateTime->now->set_time_zone( 'Australia/Sydney' );
  my $first = DateTime
                ->last_day_of_month( year => 2003, month => 3 )
                ->add( days => 1 )
                ->subtract( seconds => 1 );

Class Methods

How Date Math is Done

It's important to have some understanding of how date math is implemented in order to effectively use this module and DateTime::Duration.

The parts of a duration can be broken down into five parts. These are months, days, minutes, seconds, and nanoseconds. Adding one month to a date is different than adding 4 weeks or 28, 29, 30, or 31 days. Similarly, due to DST and leap seconds, adding a day can be different than adding 86,400 seconds, and adding a minute is not exactly the same as 60 seconds.

DateTime.pm always adds (or subtracts) days, then months, minutes, and then seconds and nanoseconds. If there are any boundary overflows, these are normalized at each step.

This means that adding one month and one day to February 28, 2003 will produce the date April 1, 2003, not March 29, 2003.

  my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
  $dt->add( months => 1, days => 1 );
  # 2003-04-01 - the result

On the other hand, if we add months first, and then separately add days, we end up with March 29, 2003:

  $dt->add( months => 1 )->add( days => 1 );
  # 2003-03-29

Leap Seconds and Date Math

The presence of leap seconds can cause some strange anomalies in date math. For example, the following is a legal datetime:

  my $dt = DateTime->new( year => 1971, month => 12, day => 31,
                          hour => 23, minute => 59, second => 60,
                          time_zone => 'UTC' );

If we do the following:

 $dt->add( months => 1 );

Then the datetime is now ``1972-02-01 00:00:00'', because there is no 23:59:60 on 1972-01-31.

Leap seconds also force us to distinguish between minutes and seconds during date math. Given the following datetime:

  my $dt = DateTime->new( year => 1971, month => 12, day => 31,
                          hour => 23, minute => 59, second => 30,
                          time_zone => 'UTC' );

we will get different results when adding 1 minute than we get if we add 60 seconds. This is because in this case, the last minute of the day, beginning at 23:59:00, actually contains 61 seconds.

Here are the results we get:

  # 1971-12-31 23:59:30 - our starting datetime
  $dt->clone->add( minutes => 1 );
  # 1972-01-01 00:00:30 - one minute later
  $dt->clone->add( seconds => 60 );
  # 1972-01-01 00:00:29 - 60 seconds later
  $dt->clone->add( seconds => 61 );
  # 1972-01-01 00:00:30 - 61 seconds later

Local vs. UTC and 24 hours vs. 1 day

When doing date math, you are changing the local datetime. This is generally the same as changing the UTC datetime, except when a change crosses a daylight saving boundary. The net effect of this is that a single day may have more or less than 24 hours.

Specifically, if you do this:

  my $dt = DateTime->new( year => 2003, month => 4, day => 5,
                          hour => 2,
                          time_zone => 'America/Chicago',
                        );
  $dt->add( days => 1 );

then you will produce an invalid local time, and therefore an exception will be thrown.

However, this works:

  my $dt = DateTime->new( year => 2003, month => 4, day => 5,
                          hour => 2,
                          time_zone => 'America/Chicago',
                        );
  $dt->add( hours => 24 );

and produces a datetime with the local time of ``03:00''.

Another way of thinking of this is that when doing date math, each of the seconds, minutes, days, and months components is added separately to the local time.

So when we add 1 day to ``2003-02-22 12:00:00'' we are incrementing day component, 22, by one in order to produce 23. If we add 24 hours, however, we're adding ``24 * 60'' minutes to the time component, and then normalizing the result (because there is no ``36:00:00'').

If all this makes your head hurt, there is a simple alternative. Just convert your datetime object to the ``UTC'' time zone before doing date math on it, and switch it back to the local time zone afterwards. This avoids the possibility of having date math throw an exception, and makes sure that 1 day equals 24 hours. Of course, this may not always be desirable, so caveat user!

The Results of Date Math

Because date math is done on each unit separately, the results of date math may not always be what you expect.

As we mentioned earlier, internally a duration is made up internally of five different units: months, days, minutes, seconds, and nanoseconds.

Given any pair of units, we cannot convert between them, except for seconds and nanoseconds, because there is no fixed conversion between the two units, because of things like leap seconds, DST changes, etc.

Here's an example, based on a question from Mark Fowler to the datetime@perl.org list.

If you want to know how many seconds a duration really represents, you have to add it to a datetime to find out, so you could do:

 my $now = DateTime->now( time_zone => 'UTC' );
 my $later = $now->clone->add_duration($duration);
 my $seconds_dur = $later->subtract_datetime_absolute($now);

This returns a duration which only contains seconds and nanoseconds.

If we were add the duration to a different datetime object we might get a different number of seconds.

There are other subtract/delta methods in DateTime.pm to generate different types of durations. These methods are subtract_datetime(), subtract_datetime_absolute(), delta_md(), delta_days(), and delta_ms().

Overloading

This module explicitly overloads the addition (+), subtraction (-), string and numeric comparison operators. This means that the following all do sensible things:

  my $new_dt = $dt + $duration_obj;
  my $new_dt = $dt - $duration_obj;
  my $duration_obj = $dt - $new_dt;
  foreach my $dt ( sort @dts ) { ... }

Additionally, the fallback parameter is set to true, so other derivable operators (+=, -=, etc.) will work properly. Do not expect increment (++) or decrement (--) to do anything useful.

The module also overloads stringification to use the iso8601() method.

Formatters And Stringification

You can optionally specify a ``formatter'', which is usually a DateTime::Format::* object/class, to control how the stringification of the DateTime object.

Any of the constructor methods can accept a formatter argument:

  my $formatter = DateTime::Format::Strptime->new(...);
  my $dt = DateTime->new(year => 2004, formatter => $formatter);

Or, you can set it afterwards:

  $dt->set_formatter($formatter);
  $formatter = $dt->formatter();

Once you set the formatter, the overloaded stringification method will use the formatter. If unspecified, the iso8601() method is used.

A formatter can be handy when you know that in your application you want to stringify your DateTime objects into a special format all the time, for example to a different language.

strftime Specifiers

The following specifiers are allowed in the format string given to the strftime() method:


DateTime.pm and Storable

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


SUPPORT

Support for this module is provided via the datetime@perl.org email list. See http://lists.perl.org/ for more details.

Please submit bugs to the CPAN RT system at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=datetime or via email at bug-datetime@rt.cpan.org.


AUTHOR

Dave Rolsky <autarch@urth.org>

However, please see the CREDITS file for more details on who I really stole all the code from.


COPYRIGHT

Copyright (c) 2003-2005 David Rolsky. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Portions of the code in this distribution are derived from other works. Please see the CREDITS file for more details.

The full text of the license can be found in the LICENSE file included with this module.


SEE ALSO

datetime@perl.org mailing list

http://datetime.perl.org/

 DateTime - A date and time object