man > DateTime

๐Ÿ“› NAME

DateTime - A date and time object for Perl

๐Ÿท๏ธ VERSION

version 1.55

๐Ÿš€ Quick Reference

Use CaseCommandDescription
Create a DateTimeDateTime->new(year => ..., month => ..., ...)Create a new datetime object from components.
Create from epochDateTime->from_epoch(epoch => time)Create a datetime object from a Unix timestamp.
Get current datetimeDateTime->nowReturns a DateTime object for the current time.
Get year/month/day$dt->year, $dt->month, $dt->dayAccess individual date components.
Get hour/minute/second$dt->hour, $dt->minute, $dt->secondAccess individual time components.
Format as ISO8601$dt->iso8601Returns something like 2022-02-06T12:00:00.
Add duration$dt->add(days => 1)Add a duration to the datetime.
Subtract duration$dt->subtract(hours => 3)Subtract a duration from the datetime.
Difference between dates$dt1 - $dt2Returns a DateTime::Duration object.
Set time zone$dt->set_time_zone('America/Chicago')Change the time zone of the object.

๐Ÿ“‹ SYNOPSIS

use DateTime;

$dt = DateTime->new(
    year       => 1964,
    month      => 10,
    day        => 16,
    hour       => 16,
    minute     => 12,
    second     => 47,
    nanosecond => 500000000,
    time_zone  => 'Asia/Taipei',
);

$dt = DateTime->from_epoch( epoch => $epoch );
$dt = DateTime->now;    # same as ( epoch => time )

$year  = $dt->year;
$month = $dt->month;        # 1-12
$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!)

# ... and many more methods ...
$ymd = $dt->ymd;         # 2002-12-06
$hms = $dt->hms;         # 14:02:29

$dt2 = $dt + $duration_object;
$dt3 = $dt - $duration_object;
$duration_object = $dt - $dt2;

$dt->set( year => 1882 );
$dt->set_time_zone('America/Chicago');
$dt->set_formatter($formatter);

๐Ÿ“ DESCRIPTION

DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project.

It represents the proleptic Gregorian calendar. The first day of the calendar (the epoch), is the first day of year 1, which corresponds to the date which was (incorrectly) believed to be the birth of Jesus Christ.

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

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

โš™๏ธ USAGE

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

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". 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. There is a year 0. There is no "quarter_0" method.

โš ๏ธ Error Handling

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

๐ŸŒ Locales

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.

๐Ÿช Floating DateTimes

The default time zone for new DateTime objects, except where stated otherwise, is the "floating" time zone. 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. 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.

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

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

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.

๐Ÿ”ฎ 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.

๐ŸŒ 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. Before setting this variable, you are strongly encouraged to audit your CPAN dependencies to see how they use "DateTime".

๐Ÿ“ 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.

๐Ÿ› ๏ธ METHODS

๐Ÿ—๏ธ Constructors

All constructors can die when invalid parameters are given.

๐Ÿ”ธ Warnings

Currently, constructors will warn if you try to create a far future DateTime (year >= 5000) with any time zone besides floating or UTC. All warnings from DateTime use the "DateTime" category and can be suppressed with:

no warnings 'DateTime';

๐Ÿ”ธ DateTime->new( ... )

This class method accepts the following parameters (defaults are 1, 1, 0, 0, 0, 0, 'floating', 'en-US'):

๐Ÿ”ธ Parsing Dates

This module does not parse dates! Instead, take a look at the various DateTime::Format::* modules on CPAN.

๐Ÿ”ธ Ambiguous Local Times

Because of Daylight Saving Time, it is possible to specify a local time that is ambiguous. If you specify an ambiguous time, then the latest UTC time is always used, in effect always choosing standard time. You can subtract an hour from the object to move to saving time.

๐Ÿ”ธ Invalid Local Times

Certain local times just do not exist due to DST transitions (e.g., 02:00:00 on April 6, 2003 in the US). Attempting to create an invalid time currently causes a fatal error.

๐Ÿ”ธ DateTime->from_epoch( epoch => $epoch, ... )

This class method constructs a new DateTime object from an epoch time. It accepts "time_zone", "locale", and "formatter" parameters. By default, the returned object will be in the UTC time zone. If you pass a "time_zone", this time zone will be applied after the object is constructed.

๐Ÿ”ธ DateTime->now( ... )

This class method is equivalent to calling "from_epoch" with the value returned from Perl's "time" function. For sub-second resolution, use the DateTime::HiRes module.

๐Ÿ”ธ 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 the "new" method, except for "day". Both "year" and "month" are required.

๐Ÿ”ธ DateTime->from_day_of_year( ... )

This constructor takes the same arguments as the "new" method, except it does not accept a "month" or "day" argument. Instead, it requires both "year" and "day_of_year".

๐Ÿ”ธ DateTime->from_object( object => $object, ... )

This class method constructs a new DateTime object from any object that implements the "utc_rd_values" method.

๐Ÿ”ธ $dt->clone

This object method returns a new object that is replica of the object upon which the method is called.

๐Ÿ” "Get" Methods

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

โœ๏ธ "Set" Methods

The remaining methods, except where otherwise specified, return the object itself, thus making method chaining possible.

๐Ÿ”ธ $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". Do not use this method to do date math. Use the "add" and "subtract" methods instead.

๐Ÿ”ธ $dt->set_year, $dt->set_month, etc.

DateTime has a "set_*" method for every item that can be passed to the constructor. These are shortcuts to calling "set" with a single key.

๐Ÿ”ธ $dt->truncate( to => ... )

This method allows you to reset some of the local time components to their "zero" values. The "to" parameter may be one of "year", "quarter", "month", "week", "local_week", "day", "hour", "minute", or "second".

๐Ÿ”ธ $dt->set_locale($locale)

Sets the object's locale.

๐Ÿ”ธ $dt->set_time_zone($tz)

This method accepts either a time zone object or a string. If the new time zone's offset is different, the local time is adjusted accordingly.

๐Ÿ”ธ $dt->set_formatter($formatter)

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

๐Ÿงฎ Math Methods

Like the set methods, math related methods always return the object itself.

๐Ÿ”ธ $dt->add_duration($duration_object)

This method adds a DateTime::Duration to the current datetime.

๐Ÿ”ธ $dt->add( parameters for DateTime::Duration )

Syntactic sugar around $dt->add_duration.

๐Ÿ”ธ $dt->subtract_duration($duration_object)

Inverts the duration and adds it.

๐Ÿ”ธ $dt->subtract( parameters )

Syntactic sugar for $dt->subtract_duration.

๐Ÿ”ธ $dt->subtract_datetime($datetime)

Returns a new DateTime::Duration object representing the difference between the two dates. The duration is relative.

๐Ÿ”ธ $dt->delta_md($datetime), $dt->delta_days($datetime)

Each returns a new DateTime::Duration object representing some portion of the difference. These methods always return a positive duration.

๐Ÿ”ธ $dt->delta_ms($datetime)

Returns a duration which contains only minutes and seconds. Always positive.

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

Returns a new DateTime::Duration object representing the difference in seconds and nanoseconds. This is the only way to accurately measure the absolute amount of time between two datetimes.

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

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

๐Ÿ“ฆ Class Methods

๐Ÿ”ธ DateTime->DefaultLocale($locale)

Specify the default locale to be used when creating DateTime objects. If unset, then "en-US" is used.

๐Ÿ”ธ DateTime->compare( $dt1, $dt2 ), DateTime->compare_ignore_floating( $dt1, $dt2 )

Compares two DateTime objects. Returns -1, 0, 1 as with Perl's "sort" function. compare_ignore_floating treats floating time zones as UTC for consistent sorting.

๐Ÿงช Testing Code That Uses DateTime

You can override "CORE::GLOBAL::time" before loading DateTime, or override "DateTime::_core_time":

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

๐Ÿง  How DateTime Math Works

๐Ÿ”ธ Making Things Simple

๐Ÿ”ธ Adding a Duration to a DateTime

DateTime always adds (or subtracts) days, then months, minutes, and then seconds and nanoseconds. If there are any boundary overflows, these are normalized at each step. This means that adding one month and one day to February 28, 2003 will produce the date April 1, 2003, not March 29, 2003.

๐Ÿ”ธ DateTime Subtraction

Date subtraction is done based solely on the two object's local datetimes, with one exception to handle DST changes. If the two objects are in different time zones, one is converted to the other's time zone first.

๐Ÿ”ธ Reversibility

Date math operations are not always reversible due to the order of addition operations. Adding 1 day and 3 minutes in one call is not the same as first adding 3 minutes and then 1 day.

๐Ÿ”ธ Leap Seconds and Date Math

The presence of leap seconds can cause anomalies. For example, the last minute of 1972-12-31 contains 61 seconds. Adding 1 minute is different from adding 60 seconds on that date.

๐Ÿ”ธ Local vs. UTC and 24 hours vs. 1 day

When math crosses a DST boundary, a single day may have more or less than 24 hours. Converting to UTC before math avoids these issues.

๐Ÿ”— Overloading

This module explicitly overloads the addition (+), subtraction (-), string and numeric comparison operators.

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

Using "==" or "<=>" to compare a DateTime object with a non-DateTime object will result in an exception. Use sort { $a cmp $b } @dates to safely sort mixed lists.

๐ŸŽจ Formatters And Stringification

You can optionally specify a "formatter", usually a "DateTime::Format::*" object or class, to control the stringification of the DateTime object.

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

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

๐Ÿ“œ CLDR Patterns

The CLDR pattern language is more powerful and complex than strftime. Patterns are simply letters without any prefix. Surround literal text with single quotes ('').

๐Ÿ•ฐ๏ธ strftime Patterns

๐Ÿ’พ DateTime and Storable

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

๐Ÿ› ๏ธ DEVELOPMENT TOOLS

If you're working on the code base, there are a few extra non-Perl tools that you may find useful, notably precious, a meta-linter/tidier. Run "precious tidy -a" to tidy all tidyable files, and "precious lint -a" to run all lint checks.

๐ŸŒณ THE DATETIME PROJECT ECOSYSTEM

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

๐Ÿ“„ Format Modules

Parse and format datetimes. All start with DateTime::Format::.

๐Ÿ“… Calendar Modules

Implement non-Gregorian calendars. All start with DateTime::Calendar::.

๐Ÿ“† Event Modules

Calculate dates for events. All start with DateTime::Event::.

โž• Others

Many other modules work with DateTime, including modules in the DateTimeX namespace.

๐Ÿ› 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.

๐Ÿ”— SEE ALSO

A Date with Perl (presentation). datetime AT perl.org mailing list.

๐Ÿ“ž SUPPORT

Bugs may be submitted at GitHub. There is a mailing list available for users of this distribution.

๐Ÿ“‚ SOURCE

The source code repository for DateTime can be found at GitHub.

โค๏ธ 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.

โœ๏ธ AUTHOR

Dave Rolsky

๐Ÿ‘ฅ CONTRIBUTORS

Ben Bennett, Christian Hansen, Daisuke Maki, Dan Book, Dan Stewart, David Dyck, David E. Wheeler, David Precious, Doug Bell, Flรกvio Soibelmann Glock, Gianni Ceccarelli, Gregory Oschwald, Hauke D, Iain Truskett, Jason McIntosh, Joshua Hoblitt, Karen Etheridge, Mark Overmeer, Michael Conrad, Michael R. Davis, Mohammad S Anwar, M Somerville, Nick Tonkin, Olaf Alders, Ovid, Paul Howarth, Philippe Bruhat (BooK), philip r brenan, Ricardo Signes, Richard Bowen, Ron Hill, Sam Kington, viviparous

ยฉ๏ธ COPYRIGHT AND LICENSE

This software is Copyright (c) 2003 - 2021 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible).

DateTime
๐Ÿ“› NAME ๐Ÿท๏ธ VERSION ๐Ÿš€ Quick Reference ๐Ÿ“‹ SYNOPSIS ๐Ÿ“ DESCRIPTION โš™๏ธ USAGE
๐Ÿ”ข 0-based Versus 1-based Numbers โš ๏ธ Error Handling ๐ŸŒ Locales ๐Ÿช Floating DateTimes ๐Ÿงฎ Math ๐Ÿข Determining the Local Time Zone Can Be Slow ๐Ÿ”ฎ Far Future DST ๐ŸŒ Globally Setting a Default Time Zone ๐Ÿ“ Upper and Lower Bounds
๐Ÿ› ๏ธ METHODS
๐Ÿ—๏ธ Constructors ๐Ÿ” "Get" Methods โœ๏ธ "Set" Methods ๐Ÿงฎ Math Methods ๐Ÿ“ฆ Class Methods ๐Ÿงช Testing Code That Uses DateTime ๐Ÿง  How DateTime Math Works ๐Ÿ”— Overloading ๐ŸŽจ Formatters And Stringification ๐Ÿ“œ CLDR Patterns ๐Ÿ•ฐ๏ธ strftime Patterns ๐Ÿ’พ DateTime and Storable
๐Ÿ› ๏ธ DEVELOPMENT TOOLS ๐ŸŒณ THE DATETIME PROJECT ECOSYSTEM
๐Ÿ“„ Format Modules ๐Ÿ“… Calendar Modules ๐Ÿ“† Event Modules โž• Others
๐Ÿ› KNOWN BUGS ๐Ÿ”— SEE ALSO ๐Ÿ“ž SUPPORT ๐Ÿ“‚ SOURCE โค๏ธ DONATIONS โœ๏ธ AUTHOR ๐Ÿ‘ฅ CONTRIBUTORS ยฉ๏ธ COPYRIGHT AND LICENSE

Generated by phpman v4.9.26-1-g511901d · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-08-04 07:39 @216.73.216.183
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format

^_top_^