DateTime(3)

๐ŸŒธ NAME ๐ŸŒธ

DateTime - A date and time object for Perl. (yep bestie, this is literally the DateTime(3) manual page from User Contributed Perl Documentation โ€” iconic behavior only ๐Ÿ’…)

โœจ VERSION โœจ

version 1.65 (that's the version, no cap)


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

okay so here's the whole vibe in code, and every line is doing its job:

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

periodt โ€” that's the synopsis, bestie. every line matters. โœจ

๐ŸŒˆ DESCRIPTION ๐ŸŒˆ

okay so DateTime is a class for the representation of date/time combinations, and it's part of the Perl DateTime project. 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 it differs from how dates are often written using "BCE/CE" or "BC/AD".

For infinite datetimes, please see the DateTime::Infinite module. iykyk, infinite time is a whole other vibe.

๐Ÿ’– USAGE ๐Ÿ’–

๐Ÿ”ข 0-based Versus 1-based Numbers

The DateTime module follows a simple logic for determining whether or not a given number is 0-based or 1-based. lowkey it's giving "just memorize the rules" energy, but it's fine.

  • 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. just so you know, bestie.

๐Ÿ˜ญ 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. so like, getters are safe, changing things can be spicy.

๐ŸŽ€ Locales

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. If this is not set, then en-US is used. default locale behavior, slay.

๐Ÿฆ‹ 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. fr fr, don't mix them โ€” it's giving chaos.

๐Ÿงฎ Math

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

โณ Determining the Local Time Zone 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:

    my $local_time_zone = DateTime::TimeZone->new( name => 'local' );

    # then everywhere else

    my $dt = DateTime->new( ..., time_zone => $local_time_zone );

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. so cache it yourself if you're making a bunch of them.

๐ŸŒž Far Future DST

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. like, do not do it. your RAM will absolutely suffer.

๐Ÿšจ Globally Setting a Default Time Zone

โš ๏ธ Warning: This is very dangerous. Do this at your own risk!

By default, DateTime uses either the floating time zone or UTC for newly created objects, depending on the constructor.

You can force DateTime to use a different time zone by setting the PERL_DATETIME_DEFAULT_TZ environment variable.

As noted above, this is very dangerous, as it affects all code that creates a DateTime object, including modules from CPAN. If those modules expect the normal default, then setting this can cause confusing breakage or subtly broken data. Before setting this variable, you are strongly encouraged to audit your CPAN dependencies to see how they use DateTime. Try running the test suite for each dependency with this environment variable set before using this in production. ngl, this is the "please think before you ship" part.

๐Ÿ“ Upper and Lower Bounds

Internally, dates are represented the number of days before or after 0001-01-01. This is stored as an integer, meaning that the upper and lower bounds are based on your Perl's integer size ($Config{ivsize}).

The limit on 32-bit systems is around 2^29 days, which gets you to year (+/-)1,469,903. On a 64-bit system you get 2^62 days, to year (+/-)12,626,367,463,883,278 (12.626 quadrillion). big numbers, big vibes.

๐Ÿ”ฅ METHODS ๐Ÿ”ฅ

DateTime provides many methods. The documentation breaks them down into groups based on what they do (constructor, accessors, modifiers, etc.).

๐Ÿ›  Constructors

All constructors can die when invalid parameters are given. so like, feed them valid stuff or they will absolutely die.

โš ๏ธ Warnings

Currently, constructors will warn if you try to create a far future DateTime (year >= 5000) with any time zone besides floating or UTC. This can be very slow if the time zone has future DST transitions that need to be calculated. If the date is sufficiently far in the future this can be really slow (minutes).

All warnings from DateTime use the DateTime category and can be suppressed with:

    no warnings 'DateTime';

This warning may be removed in the future if DateTime::TimeZone is made much faster.

๐Ÿ’– DateTime->new( ... )

    my $dt = DateTime->new(
        year       => 1966,
        month      => 10,
        day        => 25,
        hour       => 7,
        minute     => 15,
        second     => 47,
        nanosecond => 500000000,
        time_zone  => 'America/Chicago',
    );

This class method accepts the following parameters:

  • year โ€” An integer year for the DateTime. This can be any integer number within the valid range for your system (see "Upper and Lower Bounds"). This is required. like, you literally cannot skip it.
  • month โ€” An integer from 1-12. Defaults to 1.
  • day โ€” An integer from 1-31. The value will be validated based on the month, to prevent creating invalid dates like February 30. Defaults to 1.
  • hour โ€” An integer from 0-23. Hour 0 is midnight at the beginning of the given date. Defaults to 0.
  • minute โ€” An integer from 0-59. Defaults to 0.
  • second โ€” An integer from 0-61. Values of 60 or 61 are only allowed when the specified date and time have a leap second. Defaults to 0.
  • nanosecond โ€” An integer that is greater than or equal to 0. If this number is greater than 1 billion, it will be normalized into the second value for the DateTime object. Defaults to 0.
  • locale โ€” A string containing a locale code, like en-US or zh-Hant-TW, or an object returned by DateTime::Locale->load. See the DateTime::Locale documentation for details. Defaults to the value of DateTime->DefaultLocale, or en-US if the class default has not been set.
  • time_zone โ€” A string containing a time zone name like America/Chicago or a DateTime::TimeZone object. Defaults to the value of $ENV{PERL_DATETIME_DEFAULT_TZ} or floating if that env var is not set. See "Globally Setting a Default Time Zone" for more details on that env var (and why you should not use it). 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. like, it's flexible but read the docs, bestie.
  • formatter โ€” An object or class name with a format_datetime method. This will be used to stringify the DateTime object. This is optional. If it is not specified, then stringification calls $self->iso8601.

Invalid parameter types (like an array reference) will cause the constructor to die. so no arrayrefs, okay? it will literally die.

๐Ÿ“… Parsing Dates

okay so the biggest thing first, and I need you to hear me on this: this module does not parse dates! Like, there is genuinely no constructor where you can just hand it "March 3, 1970 12:34" and vibe. ๐Ÿ’€

So instead, go look at the various DateTime::Format::* modules on CPAN (https://metacpan.org/search?q=datetime%3A%3Aformat). Those bad boys parse all sorts of different date formats, and you are bound to find something that handles your particular needs. ๐Ÿซถ

๐Ÿ•ฐ๏ธ Ambiguous Local Times ๐Ÿ•ฐ๏ธ

Because of Daylight Saving Time, it's possible to specify a local time that is ambiguous. For example, in the US in 2003, the transition from 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). Which means the hour from 01:00:00 through 01:59:59 actually occurs twice, even though the UTC time just keeps moving forward. time is a lie, etc etc. ๐Ÿ˜ญ

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 from 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. That's a genuinely good way to make sure 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 changed from 01:59:59 (standard time) to 03:00:00 (saving time). This means there is no 02:00:00 through 02:59:59 on April 6! Like it's just gone. didn't happen. not invited. ๐Ÿ™ˆ

Attempting to create an invalid time currently causes a fatal error. ๐Ÿ’€

okay now the constructors, this is the good stuff โœจ

DateTime->from_epoch( epoch => $epoch, ... )

This class method can be used to construct a new DateTime object from an epoch time instead of components. Just as with the new method, it accepts time_zone, locale, and formatter parameters.

You can also call it with a single unnamed argument, which will be treated as the epoch value.

If the epoch value is a non-integral value, it will be rounded to nearest microsecond.

By default, the returned object will be in the UTC time zone.

If you pass a time_zone, then this time zone will be applied after the object is constructed. In other words, the epoch value is always interpreted as being in the UTC time zone. Here's an example:

my $dt = DateTime->from_epoch(
    epoch     => 0,
    time_zone => 'Asia/Tokyo'
);
say $dt; # Prints 1970-01-01T09:00:00 as Asia/Tokyo is +09:00 from UTC.
$dt->set_time_zone('UTC');
say $dt; # Prints 1970-01-01T00:00:00

DateTime->now( ... )

This class method is equivalent to calling from_epoch with the value returned from Perl's time function. Just as with the new method, it accepts time_zone and locale parameters.

By default, the returned object will be in the UTC time zone.

If you want sub-second resolution, use the DateTime::HiRes module's DateTime::HiRes->now method instead. ๐ŸŒธ

DateTime->today( ... )

This class method is equivalent to:

DateTime->now(@_)->truncate( to => 'day' );

DateTime->last_day_of_month( ... )

This constructor takes the same arguments as can be given to the new method, except for day. Additionally, both year and month are required.

DateTime->from_day_of_year( ... )

This constructor takes the same arguments as can be given to the new method, except that it does not accept a month or day argument. Instead, it requires both year and day_of_year. The day of year must be between 1 and 366, and 366 is only allowed for leap years. ๐Ÿฆ‹

DateTime->from_object( object => $object, ... )

This class method can be used to construct a new DateTime object from any object that implements the utc_rd_values method. All DateTime::Calendar modules must implement this method in order to provide cross-calendar compatibility. This method accepts a locale and formatter parameter. (no period at the end there, that's just how it is, we love a lawless sentence ๐Ÿ’…)

If the object passed to this method has a time_zone method, that is used to set the time zone of the newly created DateTime object.

Otherwise, the returned object will be in the floating time zone.

$dt->clone

This object method returns a new object that is a replica of the object upon which the method is called. iconic copy-paste behaviour, honestly. ๐Ÿ‘‘


๐ŸŽ€ "Get" Methods ๐ŸŽ€

This class has many methods for retrieving information about an object. buckle up bestie, this is a long list and they're all little legends:

  • $dt->year โ€” Returns the year.
  • $dt->ce_year โ€” Returns the year according to the BCE/CE numbering system. The year before year 1 in this system is year -1, aka "1 BCE".
  • $dt->era_name โ€” Returns the long name of the current era, something like "Before Christ". See the "Locales" section for more details.
  • $dt->era_abbr โ€” Returns the abbreviated name of the current era, something like "BC". See the "Locales" section for more details.
  • $dt->christian_era โ€” Returns a string, either "BC" or "AD", according to the year.
  • $dt->secular_era โ€” Returns a string, either "BCE" or "CE", according to the year.
  • $dt->year_with_era โ€” Returns a string containing the year immediately followed by the appropriate era abbreviation, based on the object's locale. The year is the absolute value of ce_year, so that year 1 is "1" and year 0 is "1BC". See the "Locales" section for more details.
  • $dt->year_with_christian_era โ€” Like year_with_era, but uses the christian_era method to get the era name.
  • $dt->year_with_secular_era โ€” Like year_with_era, but uses the secular_era method to get the era name.
  • $dt->month โ€” Returns the month of the year, from 1..12. Also available as $dt->mon.
  • $dt->month_name โ€” Returns the name of the current month. See the "Locales" section for more details.
  • $dt->month_abbr โ€” Returns the abbreviated name of the current month. See the "Locales" section for more details.
  • $dt->day โ€” Returns the day of the month, from 1..31. Also available as $dt->mday and $dt->day_of_month.
  • $dt->day_of_week โ€” Returns the day of the week as a number, from 1..7, with 1 being Monday and 7 being Sunday. Also available as $dt->wday and $dt->dow.
  • $dt->local_day_of_week โ€” Returns the day of the week as a number, from 1..7. The day corresponding to 1 will vary based on the locale. See the "Locales" section for more details.
  • $dt->day_name โ€” Returns the name of the current day of the week. See the "Locales" section for more details.
  • $dt->day_abbr โ€” Returns the abbreviated name of the current day of the week. See the "Locales" section for more details.
  • $dt->day_of_year โ€” Returns the day of the year. Also available as $dt->doy.
  • $dt->quarter โ€” Returns the quarter of the year, from 1..4.
  • $dt->quarter_name โ€” Returns the name of the current quarter. See the "Locales" section for more details.
  • $dt->quarter_abbr โ€” Returns the abbreviated name of the current quarter. See the "Locales" section for more details.
  • $dt->day_of_quarter โ€” Returns the day of the quarter. Also available as $dt->doq.
  • $dt->weekday_of_month โ€” Returns a number from 1..5 indicating which week day of the month this is. For example, June 9, 2003 is the second Monday of the month, and so this method returns 2 for that date.
  • $dt->ymd($optional_separator), $dt->mdy(...), $dt->dmy(...) โ€” Each method returns the year, month, and day, in the order indicated by the method name. Years are zero-padded to four digits. Months and days are 0-padded to two digits. By default, the values are separated by a dash (-), but this can be overridden by passing a value to the method. The $dt->ymd method is also available as $dt->date.
  • $dt->hour โ€” Returns the hour of the day, from 0..23.
  • $dt->hour_1 โ€” Returns the hour of the day, from 1..24.
  • $dt->hour_12 โ€” Returns the hour of the day, from 1..12.
  • $dt->hour_12_0 โ€” Returns the hour of the day, from 0..11.
  • $dt->am_or_pm โ€” Returns the appropriate localized abbreviation, depending on the current hour.
  • $dt->minute โ€” Returns the minute of the hour, from 0..59. Also available as $dt->min.
  • $dt->second โ€” Returns the second, from 0..61. The values 60 and 61 are used for leap seconds. Also available as $dt->sec.
  • $dt->fractional_second โ€” Returns the second, as a real number from 0.0 until 61.999999999. The values 60 and 61 are used for leap seconds.
  • $dt->millisecond โ€” Returns the fractional part of the second as milliseconds (1E-3 seconds). Half a second is 500 milliseconds. This value will always be rounded down to the nearest integer.
  • $dt->microsecond โ€” Returns the fractional part of the second as microseconds (1E-6 seconds). Half a second is 500,000 microseconds. This value will always be rounded down to the nearest integer.
  • $dt->nanosecond โ€” Returns the fractional part of the second as nanoseconds (1E-9 seconds). Half a second is 500,000,000 nanoseconds.
  • $dt->hms($optional_separator) โ€” Returns the hour, minute, and second, all zero-padded to two digits. If no separator is specified, a colon (:) is used by default. Also available as $dt->time.
  • $dt->datetime($optional_separator) โ€” This method is equivalent to:
$dt->ymd('-') . 'T' . $dt->hms(':')

The $optional_separator parameter allows you to override the separator between the date and time, for e.g. $dt->datetime(q{ }).

This method is also available as $dt->iso8601, but it's not really a very good ISO8601 format, as it lacks a time zone. If called as $dt->iso8601 you cannot change the separator, as ISO8601 specifies that "T" must be used to separate them. no notes, the spec said what it said. ๐Ÿ’€

  • $dt->rfc3339 โ€” This formats a datetime in RFC3339 format. This is the same as $dt->datetime with an added offset at the end of the string except if the time zone is the floating time zone.

If the offset is '+00:00' then this is represented as 'Z'. Otherwise the offset is formatted with a leading sign (+/-) and a colon separated numeric offset with hours and minutes. If the offset has a non-zero seconds component, that is also included. โญ

  • $dt->stringify โ€” ...and this one's description rolls straight into the next part, bestie, so hold that thought ๐Ÿซถ

Okay so this method returns a stringified version of the object. ๐Ÿ’–

It's also literally how stringification overloading gets implemented. If the object has a formatter, then its format_datetime method is used to produce a string. Otherwise, this method calls $dt->iso8601 to produce a string. See "Formatters And Stringification" for the whole tea. ๐Ÿซ–

$dt->is_leap_year ๐Ÿธ

This one hands you back a boolean value saying whether or not the datetime object is in a leap year. Simple as that, no cap.

$dt->is_last_day_of_month ๐Ÿ“…

Returns a boolean value telling you whether or not this datetime object is the last day of the month.

$dt->is_last_day_of_quarter ๐ŸŒธ

Returns a boolean value telling you whether or not the datetime object happens to be the last day of the quarter.

$dt->is_last_day_of_year ๐ŸŽ†

Returns a boolean value telling you whether or not the datetime object is the last day of the year.

$dt->month_length ๐Ÿ“

Returns the number of days in the current month.

$dt->quarter_length ๐Ÿ“

Returns the number of days in the current quarter.

$dt->year_length ๐Ÿ—“๏ธ

Returns the number of days in the current year.

$dt->week ๐Ÿ—“๏ธ

my ( $week_year, $week_number ) = $dt->week;

Gives you back info about the calendar week for the date. The values it returns are also available separately through the $dt->week_year and $dt->week_number methods, so pick your fave ๐Ÿ’….

The first week of the year is defined by ISO as the one which contains the fourth day of January โ€” which is equivalent to saying it's the first week to overlap the new year by at least four days.

Typically the week year is gonna be the same as the year the object is in, but bestie, dates at the very beginning of a calendar year often end up chilling in the last week of the prior year. And same energy the other way: the final few days of the year may get placed in the first week of the next year. Time is a social construct fr fr. ๐Ÿ˜ญ

$dt->week_year

Returns the year of the week. See $dt->week for the details, iykyk.

$dt->week_number

Returns the week of the year, from 1..53. See $dt->week for the details.

$dt->week_of_month

The week of the month, from 0..5. The first week of the month is the first week that contains a Thursday. This is based on the ICU definition of week of month, and it correlates to the ISO8601 week of year definition. A day in the week before the week with the first Thursday will be week 0. Yes, week zero is a real thing, she's just built different. ๐Ÿ’€

$dt->jd, $dt->mjd ๐ŸŒŒ

These return the Julian Day and Modified Julian Day, respectively. The value returned is a floating point number, and the fractional portion of that number represents the time portion of the datetime.

The Julian Day is a count of days since the beginning of the Julian Period, which starts with day 0 at noon on January 1, -4712.

The Modified Julian Day is a count of days since midnight on November 17, 1858.

These methods always refer to the local time, so the Julian Day is the same for a given datetime regardless of its time zone. Or, in other words: 2020-12-04T13:01:57 in America/Chicago has the same Julian Day as 2020-12-04T13:01:57 in Asia/Taipei. Time zones could never. ๐Ÿ‘‘

$dt->time_zone ๐ŸŒ

This returns the DateTime::TimeZone object for the datetime object.

$dt->offset โฐ

This returns the offset from UTC, in seconds, of the datetime object's time zone.

$dt->is_dst โ˜€๏ธ

Returns a boolean indicating whether or not the datetime's time zone is currently in Daylight Saving Time or not.

$dt->time_zone_long_name

This is a shortcut for $dt->time_zone->name. It's provided so that one can use %{time_zone_long_name} as a strftime format specifier. Cute, right? ๐ŸŽ€

$dt->time_zone_short_name

This method returns the time zone abbreviation for the current time zone, such as "PST" or "GMT".

โš ๏ธ These names are not definitive, and should not be used in any application intended for general use by users around the world. That's because it's possible for multiple time zones to have the same abbreviation. Big yikes if you build your whole app on "CST" and find out there are like five of them.

$dt->strftime( $format, ... ) โœจ

This method implements functionality similar to the strftime method in C. However โ€” plot twist โ€” if you give it multiple format strings, then it will return multiple scalars, one for each format string. She's generous like that.

See the "strftime Patterns" section for a list of all possible strftime patterns.

If you give a pattern that doesn't exist, then it is simply treated as text. No errors, no drama, just vibes.

Note that any deviation from the POSIX standard is probably a bug. DateTime should match the output of POSIX::strftime for any given pattern. So if something's off, that's a bug report, not a personality trait. ๐Ÿซถ

$dt->format_cldr( $format, ... ) ๐ŸŒˆ

This method implements formatting based on the CLDR date patterns. If given multiple format strings, then it will return multiple scalars, one for each format string.

See the "CLDR Patterns" section for a list of all possible CLDR patterns.

If you give a pattern that doesn't exist, then it is simply treated as text. Same deal as above, bestie.

$dt->epoch โณ

Returns the UTC epoch value for the datetime object. Datetimes before the start of the epoch will be returned as a negative number โ€” she can go backwards, iconic.

The return value from this method is always an integer number of seconds.

Since the epoch does not account for leap seconds, the epoch time for 1972-12-31T23:59:60 (UTC) is exactly the same as that for 1973-01-01T00:00:00. Yeah, leap seconds really said "not today". ๐Ÿ˜ญ

$dt->hires_epoch ๐Ÿ”ฌ

Returns the epoch as a floating point number. The floating point portion of the value represents the nanosecond value of the object. This method is provided for compatibility with the Time::HiRes module.

โš ๏ธ Heads up: this method suffers from the imprecision of floating point numbers, and the result may end up rounded to an arbitrary degree depending on your platform. Floating point is lowkey a liar.
my $dt = DateTime->new( year => 2012, nanosecond => 4 );
say $dt->hires_epoch;

On my system, this simply prints 1325376000 because adding 0.000000004 to 1325376000 returns 1325376000. The nanoseconds got ate. ๐Ÿ’€

$dt->is_finite, $dt->is_infinite โ™พ๏ธ

These methods allow you to distinguish normal datetime objects from infinite ones. Infinite datetime objects are documented in DateTime::Infinite. Yes, that's a real module. Go look, she's wild.

$dt->utc_rd_values ๐ŸŒ

Returns the current UTC Rata Die days, seconds, and nanoseconds as a three element list. This exists primarily to allow other calendar modules to create objects based on the values provided by this object.

$dt->local_rd_values ๐Ÿ 

Returns the current local Rata Die days, seconds, and nanoseconds as a three element list. This exists for the benefit of other modules which might want to use this information for date math, such as DateTime::Event::Recurrence.

$dt->leap_seconds โฑ๏ธ

Returns the number of leap seconds that have happened up to the datetime represented by the object. For floating datetimes, this always returns 0. Always. No cap.

$dt->utc_rd_as_seconds

Returns the current UTC Rata Die days and seconds purely as seconds. This number ignores any fractional seconds stored in the object, as well as leap seconds.

$dt->locale ๐Ÿ—ฃ๏ธ

Returns the datetime's DateTime::Locale object.

$dt->formatter ๐ŸŽจ

Returns the current formatter object or class. See "Formatters And Stringification" for the details.


๐ŸŽ€ "Set" Methods ๐ŸŽ€

The remaining methods provided by DateTime, except where otherwise specified, return the object itself, thus making method chaining possible. And chaining is literally the moment, bestie. Chain everything. ๐Ÿ”—

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

$dt->set( .. ) ๐Ÿ› ๏ธ

This method can be used to change the local components of a date time. It accepts any parameter allowed by the new method except for locale or time_zone. Use set_locale and set_time_zone for those instead, they have their own whole thing going on.

This method performs parameter validation just like the new method.

๐Ÿšจ Do not use this method to do date math. Use the add and subtract methods instead. I'm serious, this is the classic footgun.

$dt->set_year, $dt->set_month, etc.

DateTime has a set_* method for every item that can be passed to the constructor:

  • $dt->set_year
  • $dt->set_month
  • $dt->set_day
  • $dt->set_hour
  • $dt->set_minute
  • $dt->set_second
  • $dt->set_nanosecond

These are shortcuts to calling set with a single key. They all take a single parameter. Short and sweet, we love a convenience method. ๐Ÿ’–

$dt->truncate( to => ... ) โœ‚๏ธ

This method allows you to reset some of the local time components in the object to their "zero" values. The to parameter is used to specify which values to truncate, and it may be one of year, quarter, month, week, local_week, day, hour, minute, or second.

For example, if month is specified, then the local day becomes 1, and the hour, minute, and second all become 0.

If week is given, then the datetime is set to the Monday of the week in which it occurs, and the time components are all set to 0. If you truncate to local_week, then the first day of the week is locale-dependent. For example, in the en-US locale, the first day of the week is Sunday.

$dt->set_locale($locale) ๐ŸŒ

Sets the object's locale. You can provide either a locale code like en-US or an object returned by DateTime::Locale->load.

$dt->set_time_zone($tz) ๐Ÿ•ฐ๏ธ

This method accepts either a time zone object or a string that can be passed as the name parameter to DateTime::TimeZone->new. If the new time zone's offset is different from the old time zone, then the local time is adjusted accordingly.

For example:

my $dt = DateTime->new(
    year      => 2000,
    month     => 5,
    day       => 10,
    hour      => 15,
    minute    => 15,
    time_zone => 'America/Los_Angeles',
);

print $dt->hour;    # prints 15

$dt->set_time_zone('America/Chicago');

print $dt->hour;    # prints 17

If the old time zone was a floating time zone, then no adjustments to the local time are made, except to account for leap seconds. If the new time zone is floating, then the UTC time is adjusted in order to leave the local time untouched. Floating time zones are built different, okay. ๐Ÿฆ‹

Fans of Tsai Ming-Liang's films will be happy to know that this does work:

my $dt = DateTime->now( time_zone => 'Asia/Taipei' );
$dt->set_time_zone('Europe/Paris');

Yes, now we can know "ni3 na4 bian1 ji2 dian3?" ๐ŸŽฌ

$dt->set_formatter($formatter) ๐ŸŽจ

Sets the formatter for the object. See "Formatters And Stringification" for the details.

You can set this to undef to revert to the default formatter. Clean slate, fresh start. โœจ


๐Ÿงฎ 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 );

$dt->duration_class

This returns DateTime::Duration, but exists so that a subclass of DateTime can provide a different value. Very "I'm not like other classes" of it. ๐Ÿ’…

$dt->add_duration($duration_object)

Okay so this one adds a DateTime::Duration to your current datetime โ€” easy! Peek at the DateTime::Duration docs if you want the whole tea. ๐Ÿซ–

$dt->add( parameters for DateTime::Duration )

This is literally just syntactic sugar wrapped around the $dt->add_duration method. It builds a fresh DateTime::Duration object from the params you hand it, then calls $dt->add_duration. That's it, that's the whole vibe. ๐Ÿ’…

$dt->add($duration_object)

A synonym of $dt->add_duration($duration_object). Same thing, different fit. โœจ

$dt->subtract_duration($duration_object)

Hand it a DateTime::Duration object and it calls $dur->inverse on that object, then passes that brand-new duration straight into $self->add_duration. Sneaky but iconic. ๐ŸŽ€

$dt->subtract( DateTime::Duration->new parameters )

Like $dt->add, this is syntactic sugar for the $dt->subtract_duration method.

$dt->subtract($duration_object)

A synonym of $dt->subtract_duration($duration_object).


$dt->subtract_datetime($datetime) ๐Ÿ’–

Returns a brand-new DateTime::Duration object representing the difference between the two dates. Heads up though: the duration is relative to the object you're subtracting from. So like:

    2003-03-15 00:00:00.00000000
-  2003-02-15 00:00:00.00000000
-------------------------------
= 1 month

Not me stressing that this duration is not an absolute measure of the amount of time between the two datetimes ๐Ÿ˜ญ โ€” because the length of a month varies, and also leap seconds exist and they love to ruin everything.

The returned duration may have deltas for months, days, minutes, seconds, and nanoseconds.

$dt->delta_md($datetime), $dt->delta_days($datetime) ๐Ÿฆ‹

Each of these returns a new DateTime::Duration object representing some portion of the difference between two datetimes. The $dt->delta_md method returns a duration containing only the month and day portions of the duration it represents. The $dt->delta_days method returns a duration that contains only days.

Both $dt->delta_md and $dt->delta_days truncate the duration so any fractional portion of a day just gets ignored, bye ๐Ÿ‘‹. They both only operate on the date portion of a datetime, so they effectively ignore the time zone. And unlike the subtraction methods, these two always return a positive (or zero) duration. No negativity allowed here โœจ.

$dt->delta_ms($datetime) โญ

Returns a duration containing only minutes and seconds. Any day and month differences get converted into minutes and seconds. This method always returns a positive (or zero) duration too ๐Ÿ’œ.

$dt->subtract_datetime_absolute($datetime) ๐Ÿ”ฅ

Returns a new DateTime::Duration object representing the difference between the two dates in seconds and nanoseconds. This is the only way to accurately measure the absolute amount of time between two datetimes, since units bigger than a second don't represent a fixed number of seconds. It's giving precision queen ๐Ÿ‘‘.

Careful bestie: because of leap seconds, this may not return the same result as doing this math based on the value returned by $dt->epoch.

$dt->is_between( $lower, $upper ) ๐ŸŒธ

Checks whether $dt is strictly between two other DateTime objects.

"Strictly" means $dt must be greater than $lower and less than $upper. If it's equal to either object, this method returns false. No edge-hugging, we're talking strictly in the middle ๐Ÿ’….


๐Ÿ’ซ Class Methods

DateTime->DefaultLocale($locale)

This lets you specify the default locale used when creating DateTime objects. If you don't set it, en-US is the vibe.

This exists for backwards compatibility, but it's probably best avoided ๐Ÿ™ˆ. It changes the default locale for every DateTime object created in your application โ€” even the ones created by third-party libraries that also use DateTime. That's a lot of collateral, ngl.

DateTime->compare( $dt1, $dt2 ), DateTime->compare_ignore_floating( $dt1, $dt2 )

$cmp = DateTime->compare( $dt1, $dt2 );

$cmp = DateTime->compare_ignore_floating( $dt1, $dt2 );

Compares two DateTime objects. Semantics are compatible with Perl's sort function, so it returns -1 if $dt1 < $dt2, 0 if $dt1 == $dt2, and 1 if $dt1 > $dt2. Classic.

If one of the two DateTime objects has a floating time zone, it gets converted to the time zone of the other object first. That's what you want most of the time, but it can lead to inconsistent results when you compare a bunch of DateTime objects where some are floating and some are in other time zones ๐Ÿ˜ฌ.

If you want consistent results (say, because you're sorting an array of objects), use the compare_ignore_floating method:

@dates = sort { DateTime->compare_ignore_floating( $a, $b ) } @dates;

In this case, objects with a floating time zone get sorted as if they were UTC times. Sorted, slayed, done โœ….

Since DateTime objects overload comparison operators, this:

@dates = sort @dates;

is equivalent to this:

@dates = sort { DateTime->compare( $a, $b ) } @dates;

Also! DateTime objects can be compared to any other calendar class that implements the utc_rd_values method. Flexible icon behavior ๐Ÿงš.


๐Ÿงช Testing Code That Uses DateTime

If you're trying to test code that calls and uses DateTime, you might want to explicitly set the value returned by Perl's time builtin. That builtin is called by DateTime->now and DateTime->today.

You can override CORE::GLOBAL::time, but that only works if you do it before loading DateTime. If that's inconvenient, no worries โ€” you can also override DateTime::_core_time:

no warnings 'redefine';
local *DateTime::_core_time = sub { return 42 };

DateTime is guaranteed to call this subroutine to get the current time value. You can also override the _core_time sub in a subclass of DateTime and use that. Test girlies, this one's for you ๐ŸŽ€.


๐ŸŒˆ How DateTime Math Works

It's genuinely important to have some understanding of how datetime math is implemented if you want to actually use this module and DateTime::Duration effectively. Buckle up bestie ๐Ÿซถ.

โœจ Making Things Simple

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

  • use the floating time zone

If you don't care about time zones or leap seconds, use the floating timezone:

my $dt = DateTime->now( time_zone => 'floating' );

Math done on two objects in the floating time zone produces very predictable results. Chef's kiss ๐Ÿ”ฅ.

Note that in most cases you'll want to start by creating an object in a specific zone and then convert it to the floating time zone. When an object goes from a real zone to the floating zone, the time for the object remains the same.

This means that passing the floating zone to a constructor may not do what you want ๐Ÿ‘€.

my $dt = DateTime->now( time_zone => 'floating' );

is equivalent to

my $dt = DateTime->now( time_zone => 'UTC' )->set_time_zone('floating');

This might not be what you wanted. Instead, you may prefer to do this:

my $dt = DateTime->now( time_zone => 'local' )->set_time_zone('floating');
  • use UTC for all calculations

If you do care about time zones (particularly DST) or leap seconds, try to use non-UTC time zones for presentation and user input only. Convert to UTC immediately and convert back to the local time zone for presentation:

my $dt = DateTime->new( %user_input, time_zone => $user_tz );
$dt->set_time_zone('UTC');

# do various operations - store it, retrieve it, add, subtract, etc.

$dt->set_time_zone($user_tz);
print $dt->datetime;
  • math on non-UTC time zones

If you need to do date math on objects with non-UTC time zones, please read the caveats below carefully ๐Ÿšจ. The results DateTime produces are predictable, correct, and mostly intuitive, but datetime math gets very ugly when time zones are involved, and there are a few strange corner cases involving subtraction of two datetimes across a DST change.

If you can always use the floating or UTC time zones, you can skip ahead to "Leap Seconds and Date Math".

  • date vs datetime math

If you only care about the date (calendar) portion of a datetime, use either $dt->delta_md or $dt->delta_days, not $dt->subtract_datetime. This gives you predictable, unsurprising results, free from DST-related complications. Stress-free era ๐Ÿ’œ.

  • $dt->subtract_datetime and $dt->add_duration

You must convert your datetime objects to the UTC time zone before doing date math if you want to make sure the following formulas are always true:

$dt2 - $dt1 = $dur
$dt1 + $dur = $dt2
$dt2 - $dur = $dt1

Note that using $dt->delta_days ensures this formula always works, regardless of the time zones of the objects involved, as does using $dt->subtract_datetime_absolute. Other methods of subtraction are not always reversible. Not reversible?? in this economy?? ๐Ÿ˜ญ

  • never do math on two objects where only one is in the floating time zone

The date math code accounts for leap seconds whenever the DateTime object is not in the floating time zone. If you try to do math where one object is in the floating zone and the other isn't, the results will be confusing and wrong. Just don't ๐Ÿ™ˆ.

๐ŸŽ€ Adding a Duration to a DateTime

The parts of a duration break down into five parts โ€” 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, because of DST and leap seconds, adding a day can be different than adding 86,400 seconds, and adding a minute isn't exactly the same as 60 seconds. Units are not all interchangeable bestie.

We can't convert between these units, except for seconds and nanoseconds, because there's no fixed conversion between most pairs of units. That's because of things like leap seconds, DST changes, etc. The math is mathing but only in its own way ๐Ÿ’….

DateTime always adds (or subtracts) days, then months, minutes, and then seconds and nanoseconds. If there are any boundary overflows, these get 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.

So this means adding one month and one day to February 28, 2003 will produce the date April 1, 2003 โ€” not March 29, 2003. Wild, I know ๐Ÿ˜ญ.

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

Order matters, periodt. We see similar strangeness when math crosses a DST boundary:

โญ quick note bestie: if you converted the datetime object to UTC first, youโ€™d get predictable results. no cap.

If you want to know how many seconds a DateTime::Duration object represents, you literally 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 DateTime::Duration which only contains seconds and nanoseconds.

If you add that duration to a different DateTime object, you might get a different number of seconds. itโ€™s giving โ€œsame duration, different fontโ€ ๐Ÿ˜ญ

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 following 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 the DateTime::Format::Duration module, which lets you present information from durations in many useful ways. lowkey iconic.

There are other subtract/delta methods in DateTime to generate different types of durations. These methods are $dt->subtract_datetime, $dt->subtract_datetime_absolute, $dt->delta_md, $dt->delta_days, and $dt->delta_ms.

๐Ÿ’– DateTime Subtraction ๐Ÿ’–

Date subtraction is done based solely on the two objectsโ€™ 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:

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

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

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

Nice and simple. slay.

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

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

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

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

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

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

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

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

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

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

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. the math is mathing but also not mathing ๐Ÿ’€

๐ŸŒ€ Reversibility ๐ŸŒ€

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 $dt->add is not the same as first adding 3 minutes and 1 day in two separate calls.

If we take a duration returned from $dt->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",
);

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

# gives us $dt2
$dt1->add_duration($dur);

# gives us 2003-04-05 02:58:00 - 1 hour later than $dt1
$dt2->subtract_duration($dur);

The $dt->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 the DateTime::Duration classโ€™s $dur->calendar_duration and $dur->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 add one month ...

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

... 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. not me learning that a minute can have 61 seconds ๐Ÿ˜ญ

Here are the results we get:

# 1972-12-31 23:59:30 - our starting datetime
my $dt = DateTime->new(
    year      => 1972,
    month     => 12,
    day       => 31,
    hour      => 23,
    minute    => 59,
    second    => 30,
    time_zone => 'UTC'
);

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

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

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

๐Ÿฆ‹ 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. rude, honestly.

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! ๐Ÿซถ

โœจ 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;

for 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 or class, to control the stringification of the DateTime object. itโ€™s giving โ€œlet the formatter have main character energyโ€ โœจ

Any of the constructor methods can accept a formatter argument, like, whenever you want:

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

Or set it after the fact and read it right back:

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

Once you set the formatter, the overloaded stringification method will use it. If you never specify one, the iso8601 method is used. Default behavior, iconic.

A formatter is lowkey a lifesaver when you know that in your app you want to stringify your DateTime objects into one special format all the time โ€” for example in Postgres format. ๐Ÿ’…

If you hand over a formatter class name or object, it must implement a format_datetime method. That method gets called with just the DateTime object as its one and only argument. No extras, no options, just the object. ๐Ÿซถ

๐ŸŒธ CLDR Patterns ๐ŸŒธ

Okay so the CLDR pattern language is both more powerful and more complex than strftime. Unlike strftime patterns, you often have to explicitly escape text you don't want formatted, because these patterns are literally just letters with no prefix at all. iykyk.

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 ('). And if you want an actual single quote in there, you gotta escape it as two single quotes (''). That's the whole trick, bestie:

my $pattern1 = q{'Today is ' EEEE};
my $pattern2 = q{'It is now' h 'o''clock' a};

Spaces and any non-letter text will always be passed through as-is. No notes, they just vibe through.

Many CLDR patterns that 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 hours 1-9 will have a leading zero prepended. โœจ

However โ€” and this is the โœจloreโœจ โ€” CLDR often uses five of a letter to represent the narrow form of a pattern. This inconsistency is necessary for backwards compatibility. Not a bug, it's a feature, periodt.

There are many cases where CLDR patterns distinguish 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. Context matters, always.

There are also many cases where CLDR 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. ๐Ÿ˜ญ (so like, could be Tuesday, could be Thursday, could be Thursday-but-cooler, who knows)

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. We said what we said.

The output of a CLDR pattern is always localized, when applicable. ๐Ÿฆ‹

CLDR provides the following patterns:

  • G{1,3} โ€” The abbreviated era (BC, AD).
  • GGGG โ€” The wide era (Before Christ, Anno Domini).
  • GGGGG โ€” The narrow era, if it exists (but it mostly doesn't ๐Ÿ™ˆ).
  • y and y{3,} โ€” The year, zero-prefixed as needed. Negative years will start with a -, and this will be included in the length calculation. In other words, the yyyyy pattern will format year -1234 as -1234, not -01234.
  • yy โ€” This is a special case. It always produces a two-digit year, so 1976 becomes 76. Negative years will start with a -, making them one character longer.
  • Y{1,} โ€” The year in "week of the year" calendars, from $dt->week_year.
  • u{1,} โ€” Same as y except that uu is not a special case.
  • Q{1,2} โ€” The quarter as a number (1..4).
  • QQQ โ€” The abbreviated format form for the quarter.
  • QQQQ โ€” The wide format form for the quarter.
  • q{1,2} โ€” The quarter as a number (1..4).
  • qqq โ€” The abbreviated stand-alone form for the quarter.
  • qqqq โ€” The wide stand-alone form for the quarter.
  • M{1,2} โ€” The numerical month.
  • MMM โ€” The abbreviated format form for the month.
  • MMMM โ€” The wide format form for the month.
  • MMMMM โ€” The narrow format form for the month.
  • L{1,2} โ€” The numerical month.
  • LLL โ€” The abbreviated stand-alone form for the month.
  • LLLL โ€” The wide stand-alone form for the month.
  • LLLLL โ€” The narrow stand-alone form for the month.
  • w{1,2} โ€” The week of the year, from $dt->week_number.
  • W โ€” The week of the month, from $dt->week_of_month.
  • d{1,2} โ€” The numeric day of the month.
  • D{1,3} โ€” The numeric day of the year.
  • F โ€” The day of the week in the month, from $dt->weekday_of_month.
  • g{1,} โ€” The modified Julian day, from $dt->mjd.
  • E{1,3} and eee โ€” The abbreviated format form for the day of the week.
  • EEEE and eeee โ€” The wide format form for the day of the week.
  • EEEEE and eeeee โ€” The narrow format form for the day of the week.
  • e{1,2} โ€” The local numeric day of the week, from 1 to 7. This number depends on what day is considered the first day of the week, which varies by locale. For example, in the US, Sunday is the first day of the week, so this returns 2 for Monday.
  • c โ€” The numeric day of the week from 1 to 7, treating Monday as the first of the week, regardless of locale.
  • ccc โ€” The abbreviated stand-alone form for the day of the week.
  • cccc โ€” The wide stand-alone form for the day of the week.
  • ccccc โ€” The narrow format form for the day of the week.
  • a โ€” The localized form of AM or PM for the time.
  • h{1,2} โ€” The hour from 1-12.
  • H{1,2} โ€” The hour from 0-23.
  • K{1,2} โ€” The hour from 0-11.
  • k{1,2} โ€” The hour from 1-24.
  • j{1,2} โ€” The hour, in 12 or 24 hour form, based on the preferred form for the locale. In other words, this is equivalent to either h{1,2} or H{1,2}.
  • m{1,2} โ€” The minute.
  • s{1,2} โ€” The second.
  • S{1,} โ€” The fractional portion of the seconds, rounded based on the length of the specifier. This returned without a leading decimal point, but may have leading or trailing zeroes.
  • A{1,} โ€” The millisecond of the day, based on the current time. In other words, if it is 12:00:00.00, this returns 43200000.
  • z{1,3} โ€” The time zone short name.
  • zzzz โ€” The time zone long name.
  • Z{1,3} โ€” The time zone offset.
  • ZZZZ โ€” The time zone short name and the offset as one string, so something like CDT-0500.
  • ZZZZZ โ€” The time zone offset as a sexagesimal number, so something like -05:00. (This is useful for W3C format. ๐ŸŽ€)
  • v{1,3} โ€” The time zone short name.
  • vvvv โ€” The time zone long name.
  • V{1,3} โ€” The time zone short name.
  • VVVV โ€” The time zone long name.

๐Ÿ’ซ CLDR "Available Formats" ๐Ÿ’ซ

The CLDR data includes pre-defined formats for various patterns such as "month and day" or "time of day". Using these formats lets you render information about a datetime in the most natural way for users from a given locale. It's the "make it sound human" button.

These formats are indexed by a key that is itself a CLDR pattern. When you look these up, you get back a different CLDR pattern suitable for the locale. Sneaky but slay.

Let's look at some examples โ€” we'll use 2008-02-05T18:30:30 as our example datetime value, and see how this is rendered for the en-US and fr-FR locales. ๐ŸŒˆ

  • MMMd โ€” The abbreviated month and day as number. For en-US, we get the pattern MMM d, which renders as Feb 5. For fr-FR, we get the pattern d MMM, which renders as 5 fรฉvr..
  • yQQQ โ€” The year and abbreviated quarter of year. For en-US, we get the pattern QQQ y, which renders as Q1 2008. For fr-FR, we get the same pattern, QQQ y, which renders as T1 2008.
  • hm โ€” The 12-hour time of day without seconds. For en-US, we get the pattern h:mm a, which renders as 6:30 PM. For fr-FR, we get the exact same pattern and rendering.

The available formats for each locale are documented in the POD for that locale. To get back the format, you use the $locale->format_for method. For example:

say $dt->format_cldr( $dt->locale->format_for('MMMd') );

๐Ÿซถ See? Look up the pattern, then format with it. Two-step icon behavior.

โญ strftime Patterns โญ

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

  • %a โ€” The abbreviated weekday name.
  • %A โ€” The full weekday name.
  • %b โ€” The abbreviated month name.
  • %B โ€” The full month name.
  • %c โ€” The default datetime format for the object's locale.
  • %C โ€” The century number (year/100) as a 2-digit integer.
  • %d โ€” The day of the month as a decimal number (range 01 to 31).
  • %D โ€” Equivalent to %m/%d/%y. This is not a good standard format if you want folks from both the United States and the rest of the world to understand the date! ๐Ÿ’€ (sorry to the US besties, it's just facts)
  • %e โ€” Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space.
  • %F โ€” Equivalent to %Y-%m-%d (the ISO 8601 date format).
  • %G โ€” The ISO 8601 year with century as a decimal number. The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead. (TZ)
  • %g โ€” Like %G, but without century, i.e., with a 2-digit year (00-99).
  • %h โ€” Equivalent to %b.
  • %H โ€” The hour as a decimal number using a 24-hour clock (range 00 to 23).
  • %I โ€” The hour as a decimal number using a 12-hour clock (range 01 to 12).
  • %j โ€” The day of the year as a decimal number (range 001 to 366).
  • %k โ€” The hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank. (See also %H.)
  • %l โ€” The hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank. (See also %I.)
  • %m โ€” The month as a decimal number (range 01 to 12).
  • %M โ€” The minute as a decimal number (range 00 to 59).
  • %n โ€” A newline character.
  • %N โ€” The fractional seconds digits. Default is 9 digits (nanoseconds). โญ
  • %3N โ€” milliseconds (3 digits) ๐Ÿ•ฐ๏ธ
  • %6N โ€” microseconds (6 digits) โœจ
  • %9N โ€” nanoseconds (9 digits) ๐Ÿ”ฅ
๐Ÿ’ก This value will always be rounded down to the nearest integer. No cap.
  • %p โ€” either AM or PM according to the given time value, or the corresponding strings for the current locale. Noon is treated as pm and midnight as am. ๐ŸŒž๐ŸŒ™
  • %P โ€” like %p but lowercase: am or pm, or the matching string for the current locale. ๐Ÿซถ
  • %r โ€” the time in a.m. or p.m. notation. In the POSIX locale this is equivalent to %I:%M:%S %p. โฐ
  • %R โ€” the time in 24-hour notation (%H:%M). (SU) For a version including the seconds, see %T below. ๐Ÿ•›
  • %s โ€” the number of seconds since the epoch. โณ
  • %S โ€” the second as a decimal number (range 00 to 61). ๐ŸŽ€
  • %t โ€” a tab character. โฌ…๏ธ
  • %T โ€” the time in 24-hour notation (%H:%M:%S). ๐Ÿ•ฐ๏ธ
  • %u โ€” the day of the week as a decimal, range 1 to 7, Monday being 1. See also %w. ๐Ÿ“…
  • %U โ€” the week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01. See also %V and %W. ๐Ÿ—“๏ธ
  • %V โ€” the ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. See also %U and %W. ๐ŸŒ
  • %w โ€” the day of the week as a decimal, range 0 to 6, Sunday being 0. See also %u. ๐ŸŒธ
  • %W โ€” the week number of the current year as a decimal number, range 00 to 53, starting with the first Monday as the first day of week 01. ๐Ÿ—“๏ธ
  • %x โ€” the default date format for the object's locale. ๐Ÿ’–
  • %X โ€” the default time format for the object's locale. ๐Ÿ’…
  • %y โ€” the year as a decimal number without a century (range 00 to 99). โœจ
  • %Y โ€” the year as a decimal number including the century. ๐Ÿ‘‘
  • %z โ€” the time-zone as hour offset from UTC. Required to emit RFC822-conformant dates (using "%a, %d %b %Y %H:%M:%S %z"). ๐ŸŒˆ
  • %Z โ€” the short name for the time zone, typically an abbreviation like "EST" or "AEST". ๐Ÿฆ‹
  • %% โ€” a literal % character. ๐Ÿ’ฏ
  • %{method} โ€” any method name may be specified using the format "%{method}" name where "method" is a valid DateTime object method. ๐Ÿ”ฎ

๐Ÿ’พ DateTime and Storable ๐Ÿ’พ

DateTime implements Storable hooks in order to reduce the size of a serialized DateTime object. Iconic behavior, honestly. ๐Ÿซถ

๐Ÿ› ๏ธ DEVELOPMENT TOOLS ๐Ÿ› ๏ธ

If you're working on the DateTIme code base, there are a few extra non-Perl tools that you may find useful, notably precious https://github.com/houseabsolute/precious, a meta-linter/tidier. ๐Ÿงš You can install all the necessary tools in $HOME/bin by running ./dev-bin/install-dev-tools.sh.

Try running precious tidy -a to tidy all the tidyable files in the repo, and precious lint -a to run all the lint checks. โœจ

You can enable a git pre-commit hook for linting by running ./git/setup.pl.

Note that linting will be checked in CI, and it's okay to submit a PR which fails the linting check, but it's extra nice to fix these yourself. ๐Ÿ’…

๐ŸŒ THE DATETIME PROJECT ECOSYSTEM ๐ŸŒ

This module is part of a larger ecosystem of modules in the DateTime family. It's giving whole friend group, fr fr. ๐Ÿ’–

๐Ÿ—“๏ธ DateTime::Set ๐Ÿ—“๏ธ

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:: https://metacpan.org/search?q=datetime%3A%3Aformat.

๐Ÿ“… 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:: https://metacpan.org/search?q=datetime%3A%3Acalendar.

๐ŸŽ‰ 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:: https://metacpan.org/search?q=datetime%3A%3Aevent.

๐ŸŒˆ Others ๐ŸŒˆ

There are many other modules that work with DateTime, including modules in the DateTimeX namespace https://metacpan.org/search?q=datetimex namespace, as well as others. ๐Ÿฆ‹

See MetaCPAN https://metacpan.org/search?q=datetime for more modules.

๐Ÿ’€ KNOWN BUGS ๐Ÿ’€

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. ๐Ÿ™ˆ

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

A Date with Perl http://presentations.houseabsolute.com/a-date-with-perl/ โ€” a talk I've given at a few YAPCs. ๐ŸŽค

datetime@perl.org mailing list http://lists.perl.org/list/datetime.html ๐Ÿ’Œ

๐Ÿซถ SUPPORT ๐Ÿซถ

Bugs may be submitted at https://github.com/houseabsolute/DateTime.pm/issues. ๐Ÿ›

There is a mailing list available for users of this distribution, mailto:datetime@perl.org. ๐Ÿ’–

๐Ÿ“ฆ SOURCE ๐Ÿ“ฆ

The source code repository for DateTime can be found at https://github.com/houseabsolute/DateTime.pm. ๐Ÿ‘‘

๐Ÿ’ธ DONATIONS ๐Ÿ’ธ

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 (let's all have a chuckle at that together). ๐Ÿ˜ญ

To donate, log into PayPal and send money to autarch@urth.org, or use the button at https://houseabsolute.com/foss-donations/. ๐Ÿ’ธ

โœ๏ธ AUTHOR โœ๏ธ

Dave Rolsky autarch@urth.org ๐Ÿ‘‘

๐Ÿ‘‘ CONTRIBUTORS ๐Ÿ‘‘

  • Ben Bennett <fiji@limey.net>
  • Christian Hansen <chansen@cpan.org>
  • Daisuke Maki <dmaki@cpan.org>
  • Dan Book <grinnz@gmail.com>
  • Dan Stewart <danielandrewstewart@gmail.com>
  • David Dyck <david.dyck@checksum.com>
  • David E. Wheeler <david@justatheory.com>
  • David Precious <davidp@preshweb.co.uk>
  • Doug Bell <madcityzen@gmail.com>
  • Flรกvio Soibelmann Glock <fglock@gmail.com>
  • Gianni Ceccarelli <gianni.ceccarelli@broadbean.com>
  • Gregory Oschwald <oschwald@gmail.com>
  • Hauke D <haukex@zero-g.net>
  • Iain Truskett <deceased>
  • James Raspass <jraspass@gmail.com>
  • Jason McIntosh <jmac@jmac.org>
  • Joshua Hoblitt <jhoblitt@cpan.org>
  • Karen Etheridge <ether@cpan.org>
  • Mark Overmeer <mark@overmeer.net>
  • Michael Conrad <mike@nrdvana.net>
  • Michael R. Davis <mrdvt92@users.noreply.github.com>
  • Mohammad S Anwar <mohammad.anwar@yahoo.com>
  • M Somerville <dracos@users.noreply.github.com>
  • Nick Tonkin <1nickt@users.noreply.github.com>
  • Olaf Alders <olaf@wundersolutions.com>
  • Ovid <curtis_ovid_poe@yahoo.com>
  • Paul Howarth <paul@city-fan.org>
  • Philippe Bruhat (BooK) <book@cpan.org>
  • philip r brenan <philiprbrenan@gmail.com>
  • Ricardo Signes <rjbs@cpan.org>
  • Richard Bowen <bowen@cpan.org>
  • Ron Hill <rkhill@cpan.org>
  • Sam Kington <github@illuminated.co.uk>
  • viviparous <viviparous@prc>

This software is Copyright (c) 2003 - 2023 by Dave Rolsky.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)

The full text of the license can be found in the LICENSE file included with this distribution. ๐Ÿ’–


And that's the whole page, bestie โ€” footer vibes: perl v5.42.0, dated 2024-03-08, for DateTime(3). Byeee! ๐ŸŽ€โœจ

๐Ÿ“ฆ where this page comes from