Dave Rolsky > DateTime-0.75 > DateTime



Annotate this POD (15)


New  8
Open  6
Stalled  6
View/Report Bugs
Module Version: 0.75   Source   Latest Release: DateTime-1.10


DateTime - A date and time object


version 0.75


  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

  $day    = $dt->day;            # 1-31

  $dow    = $dt->day_of_week;    # 1-7 (Monday is 1)

  $hour   = $dt->hour;           # 0-23
  $minute = $dt->minute;         # 0-59

  $second = $dt->second;         # 0-61 (leap seconds!)

  $doy    = $dt->day_of_year;    # 1-366 (leap years)

  $doq    = $dt->day_of_quarter; # 1..

  $qtr    = $dt->quarter;        # 1-4

  # all of the start-at-1 methods above have corresponding 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

  $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

  $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, ...

  # May not work for all possible datetime, see the docs on this
  # method for more details.
  $epoch_time  = $dt->epoch;

  $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 );


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/wiki/datetime/page/FAQ.

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.


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.


All the object methods which return names or abbreviations return data based on a locale. 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 "en_US" is used.

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.


If you are going to be using doing date math, please read the section "How DateTime Math Works".

Time Zone Warnings

Determining the local time zone for a system can be slow. If $ENV{TZ} is not set, it may involve reading a number of files in /etc or elsewhere. If you know that the local time zone won't change while your code is running, and you need to make many objects for the local time zone, it is strongly recommended that you retrieve the local time zone once and cache it:

  our $App::LocalTZ = DateTime::TimeZone->new( name => 'local' );

  ... # then everywhere else

  my $dt = DateTime->new( ..., time_zone => $App::LocalTZ );

DateTime itself does not do this internally because local time zones can change, and there's no good way to determine if it's changed without doing all the work to look it up.

Do not try to use named time zones (like "America/Chicago") with dates very far in the future (thousands of years). The current implementation of DateTime::TimeZone will use a huge amount of memory calculating all the DST changes from now until the future date. Use UTC or the floating time zone and you will be safe.



All constructors can die when invalid parameters are given.

Parsing Dates

This module does not parse dates! That means there is no constructor to which you can pass things like "March 3, 1970 12:34".

Instead, take a look at the various DateTime::Format::* modules on CPAN. These parse all sorts of different date formats, and you're bound to find something that can handle your particular needs.

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 );

Math Methods

Like the set methods, math related methods always return the object itself, to allow for chaining:

  $dt->add( days => 1 )->subtract( seconds => 1 );

Class Methods

How DateTime Math Works

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

Making Things Simple

If you want to simplify your life and not have to think too hard about the nitty-gritty of datetime math, I have several recommendations:

Adding a Duration to a Datetime

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.

We cannot convert between these units, except for seconds and nanoseconds, because there is no fixed conversion between the two units, because of things like leap seconds, DST changes, etc.

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. For the days and months the local (not UTC) values are used. For minutes and seconds, the local values are used. This generally just works.

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

We see similar strangeness when math crosses a DST boundary:

  my $dt = DateTime->new(
      year      => 2003,
      month     => 4,
      day       => 5,
      hour      => 1,
      minute    => 58,
      time_zone => "America/Chicago",

  $dt->add( days => 1, minutes => 3 );
  # 2003-04-06 02:01:00

  $dt->add( minutes => 3 )->add( days => 1 );
  # 2003-04-06 03:01:00

Note that if you converted the datetime object to UTC first you would get predictable results.

If you want to know how many seconds a duration object 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.

DateTime::Duration supports three different end-of-month algorithms for adding months. This comes into play when an addition results in a day past the end of the month (for example, adding one month to January 30).

 # 2010-08-31 + 1 month = 2010-10-01
 $dt->add( months => 1, end_of_month => 'wrap' );

 # 2010-01-30 + 1 month = 2010-02-28
 $dt->add( months => 1, end_of_month => 'limit' );

 # 2010-04-30 + 1 month = 2010-05-31
 $dt->add( months => 1, end_of_month => 'preserve' );

By default, it uses "wrap" for positive durations and "preserve" for negative durations. See DateTime::Duration for a detailed explanation of these algorithms.

If you need to do lots of work with durations, take a look at Rick Measham's DateTime::Format::Duration module, which lets you present information from durations in many useful ways.

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().

Datetime Subtraction

Date subtraction is done solely based on the two object's local datetimes, with one exception to handle DST changes. Also, if the two datetime objects are in different time zones, one of them is converted to the other's time zone first before subtraction. This is best explained through examples:

The first of these probably makes the most sense:

  my $dt1 = DateTime->new(
      year      => 2003,
      month     => 5,
      day       => 6,
      time_zone => 'America/Chicago',

  # not DST

  my $dt2 = DateTime->new(
      year      => 2003,
      month     => 11,
      day       => 6,
      time_zone => 'America/Chicago',

  # is DST

  my $dur = $dt2->subtract_datetime($dt1);
  # 6 months

Nice and simple.

This one is a little trickier, but still fairly logical:

  my $dt1 = DateTime->new(
      year      => 2003,
      month     => 4,
      day       => 5,
      hour      => 1,
      minute    => 58,
      time_zone => "America/Chicago",

  # is DST

  my $dt2 = DateTime->new(
      year      => 2003,
      month     => 4,
      day       => 7,
      hour      => 2,
      minute    => 1,
      time_zone => "America/Chicago",

  # not DST

  my $dur = $dt2->subtract_datetime($dt1);

  # 2 days and 3 minutes

Which contradicts the result this one gives, even though they both make sense:

  my $dt1 = DateTime->new(
      year      => 2003,
      month     => 4,
      day       => 5,
      hour      => 1,
      minute    => 58,
      time_zone => "America/Chicago",

  # is DST

  my $dt2 = DateTime->new(
      year      => 2003,
      month     => 4,
      day       => 6,
      hour      => 3,
      minute    => 1,
      time_zone => "America/Chicago",

  # not DST

  my $dur = $dt2->subtract_datetime($dt1);

  # 1 day and 3 minutes

This last example illustrates the "DST" exception mentioned earlier. The exception accounts for the fact 2003-04-06 only lasts 23 hours.

And finally:

  my $dt2 = DateTime->new(
      year      => 2003,
      month     => 10,
      day       => 26,
      hour      => 1,
      time_zone => 'America/Chicago',

  my $dt1 = $dt2->clone->subtract( hours => 1 );

  my $dur = $dt2->subtract_datetime($dt1);
  # 60 minutes

This seems obvious until you realize that subtracting 60 minutes from $dt2 in the above example still leaves the clock time at "01:00:00". This time we are accounting for a 25 hour day.


Date math operations are not always reversible. This is because of the way that addition operations are ordered. As was discussed earlier, adding 1 day and 3 minutes in one call to add() is not the same as first adding 3 minutes and 1 day in two separate calls.

If we take a duration returned from subtract_datetime() and then try to add or subtract that duration from one of the datetimes we just used, we sometimes get interesting results:

  my $dt1 = DateTime->new(
      year      => 2003,
      month     => 4,
      day       => 5,
      hour      => 1,
      minute    => 58,
      time_zone => "America/Chicago",

  my $dt2 = DateTime->new(
      year      => 2003,
      month     => 4,
      day       => 6,
      hour      => 3,
      minute    => 1,
      time_zone => "America/Chicago",

  my $dur = $dt2->subtract_datetime($dt1);
  # 1 day and 3 minutes

  # gives us $dt2

  # gives us 2003-04-05 02:58:00 - 1 hour later than $dt1

The subtract_duration() operation gives us a (perhaps) unexpected answer because it first subtracts one day to get 2003-04-05T03:01:00 and then subtracts 3 minutes to get the final result.

If we explicitly reverse the order we can get the original value of $dt1. This can be facilitated by DateTime::Duration's calendar_duration() and clock_duration() methods:

  $dt2->subtract_duration( $dur->clock_duration )
      ->subtract_duration( $dur->calendar_duration );

Leap Seconds and Date Math

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

  my $dt = DateTime->new(
      year      => 1972,
      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 "1973-02-01 00:00:00", because there is no 23:59:60 on 1973-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      => 1972,
      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:

  # 1972-12-31 23:59:30 - our starting datetime

  $dt->clone->add( minutes => 1 );
  # 1973-01-01 00:00:30 - one minute later

  $dt->clone->add( seconds => 60 );
  # 1973-01-01 00:00:29 - 60 seconds later

  $dt->clone->add( seconds => 61 );
  # 1973-01-01 00:00:30 - 61 seconds later

Local vs. UTC and 24 hours vs. 1 day

When math crosses a daylight saving boundary, a single day may have more or less than 24 hours.

For example, 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".

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!


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 string comparison operators, eq or ne, will use the string value to compare with non-DateTime objects.

DateTime objects do not have a numeric value, using == or <=> to compare a DateTime object with a non-DateTime object will result in an exception. To safely sort mixed DateTime and non-DateTime objects, use sort { $a cmp $b } @dates.

The module also overloads stringification using the object's formatter, defaulting to iso8601() method. See "Formatters And Stringification" for details.

Formatters And Stringification

You can optionally specify a "formatter", which is usually a DateTime::Format::* object/class, to control 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:

  $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.

If you provide a formatter class name or object, it must implement a format_datetime method. This method will be called with just the DateTime object as its argument.

CLDR Patterns

The CLDR pattern language is both more powerful and more complex than strftime. Unlike strftime patterns, you often have to explicitly escape text that you do not want formatted, as the patterns are simply letters without any prefix.

For example, "yyyy-MM-dd" is a valid CLDR pattern. If you want to include any lower or upper case ASCII characters as-is, you can surround them with single quotes ('). If you want to include a single quote, you must escape it as two single quotes ('').

  'Today is ' EEEE
  'It is now' h 'o''clock' a

Spaces and any non-letter text will always be passed through as-is.

Many CLDR patterns which produce numbers will pad the number with leading zeroes depending on the length of the format specifier. For example, "h" represents the current hour from 1-12. If you specify "hh" then the 1-9 will have a leading zero prepended.

However, CLDR often uses five of a letter to represent the narrow form of a pattern. This inconsistency is necessary for backwards compatibility.

CLDR often distinguishes between the "format" and "stand-alone" forms of a pattern. The format pattern is used when the thing in question is being placed into a larger string. The stand-alone form is used when displaying that item by itself, for example in a calendar.

It also often provides three sizes for each item, wide (the full name), abbreviated, and narrow. The narrow form is often just a single character, for example "T" for "Tuesday", and may not be unique.

CLDR provides a fairly complex system for localizing time zones that we ignore entirely. The time zone patterns just use the information provided by DateTime::TimeZone, and do not follow the CLDR spec.

The output of a CLDR pattern is always localized, when applicable.

CLDR provides the following patterns:

strftime Patterns

The following patterns are allowed in the format string given to the $dt->strftime() method:

DateTime.pm and Storable

DateTime implements Storable hooks in order to reduce the size of a serialized DateTime object.


This module is part of a larger ecosystem of modules in the DateTime family.


The DateTime::Set module represents sets (including recurrences) of datetimes. Many modules return sets or recurrences.

Format Modules

The various format modules exist to parse and format datetimes. For example, DateTime::Format::HTTP parses dates according to the RFC 1123 format:

  my $datetime
      = DateTime::Format::HTTP->parse_datetime('Thu Feb  3 17:03:55 GMT 1994');

  print DateTime::Format::HTTP->format_datetime($datetime);

Most format modules are suitable for use as a formatter with a DateTime object.

All format modules start with DateTime::Format::.

Calendar Modules

There are a number of modules on CPAN that implement non-Gregorian calendars, such as the Chinese, Mayan, and Julian calendars.

All calendar modules start with DateTime::Calendar::.

Event Modules

There are a number of modules that calculate the dates for events, such as Easter, Sunrise, etc.

All event modules start with DateTime::Event::.


There are many other modules that work with DateTime, including modules in the DateTimeX namespace, as well as others.

See the datetime wiki and search.cpan.org for more details.


The tests in 20infinite.t seem to fail on some machines, particularly on Win32. This appears to be related to Perl's internal handling of IEEE infinity and NaN, and seems to be highly platform/compiler/phase of moon dependent.

If you don't plan to use infinite datetimes you can probably ignore this. This will be fixed (perhaps) in future versions.


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

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


If you'd like to thank me for the work I've done on this module, please consider making a "donation" to me via PayPal. I spend a lot of free time creating free software, and would appreciate any support you'd care to offer.

Please note that I am not suggesting that you must do this in order for me to continue working on this particular software. I will continue to do so, inasmuch as I have in the past, for as long as it interests me.

Similarly, a donation made in this way will probably not make me work on this software much more, unless I get so many donations that I can consider working on free software full time, which seems unlikely at best.

To donate, log into PayPal and send money to autarch@urth.org or use the button on this page: http://www.urth.org/~autarch/fs-donation.html


datetime@perl.org mailing list



Dave Rolsky <autarch@urth.org>


This software is Copyright (c) 2012 by Dave Rolsky.

This is free software, licensed under:

  The Artistic License 2.0 (GPL Compatible)
syntax highlighting: