DateTime - A date and time object for Perl
version 1.55
| Use Case | Command | Description |
|---|---|---|
| Create a DateTime | DateTime->new(year => ..., month => ..., ...) | Create a new datetime object from components. |
| Create from epoch | DateTime->from_epoch(epoch => time) | Create a datetime object from a Unix timestamp. |
| Get current datetime | DateTime->now | Returns a DateTime object for the current time. |
| Get year/month/day | $dt->year, $dt->month, $dt->day | Access individual date components. |
| Get hour/minute/second | $dt->hour, $dt->minute, $dt->second | Access individual time components. |
| Format as ISO8601 | $dt->iso8601 | Returns 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 - $dt2 | Returns a DateTime::Duration object. |
| Set time zone | $dt->set_time_zone('America/Chicago') | Change the time zone of the object. |
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);
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.
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.
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. If this is not set, then "en-US" is used.
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.
If you are going to be doing date math, please read the section "How DateTime Math Works".
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.
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.
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".
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.
All constructors can die when invalid parameters are given.
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'):
This module does not parse dates! Instead, take a look at the various DateTime::Format::* modules on CPAN.
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.
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->cloneThis object method returns a new object that is replica of the object upon which the method is called.
This class has many methods for retrieving information about an object.
$dt->year โ Returns the year.$dt->ce_year โ Returns the year according to the BCE/CE numbering system.$dt->era_name โ Returns the long name of the current era, something like "Before Christ".$dt->era_abbr โ Returns the abbreviated name of the current era, something like "BC".$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.$dt->month (also $dt->mon) โ Returns the month of the year, from 1..12.$dt->month_name โ Returns the name of the current month.$dt->month_abbr โ Returns the abbreviated name of the current month.$dt->day (also $dt->mday, $dt->day_of_month) โ Returns the day of the month, from 1..31.$dt->day_of_week (also $dt->wday, $dt->dow) โ Returns the day of the week as a number, from 1..7, with 1 being Monday and 7 being Sunday.$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.$dt->day_name โ Returns the name of the current day of the week.$dt->day_abbr โ Returns the abbreviated name of the current day of the week.$dt->day_of_year (also $dt->doy) โ Returns the day of the year.$dt->quarter โ Returns the quarter of the year, from 1..4.$dt->quarter_name โ Returns the name of the current quarter.$dt->quarter_abbr โ Returns the abbreviated name of the current quarter.$dt->day_of_quarter (also $dt->doq) โ Returns the day of the quarter.$dt->weekday_of_month โ Returns a number from 1..5 indicating which week day of the month this is.$dt->ymd($sep), $dt->mdy($sep), $dt->dmy($sep) โ Returns the year, month, and day, in the order indicated. Zero-padded.$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 (AM/PM).$dt->minute (also $dt->min) โ Returns the minute of the hour, from 0..59.$dt->second (also $dt->sec) โ Returns the second, from 0..61.$dt->fractional_second โ Returns the second as a real number.$dt->millisecond โ Returns the fractional part of the second as milliseconds.$dt->microsecond โ Returns the fractional part of the second as microseconds.$dt->nanosecond โ Returns the fractional part of the second as nanoseconds.$dt->hms($sep) (also $dt->time) โ Returns the hour, minute, and second, zero-padded.$dt->datetime($sep) (also $dt->iso8601) โ Equivalent to $dt->ymd('-') . 'T' . $dt->hms(':').$dt->rfc3339 โ Formats a datetime in RFC3339 format.$dt->stringify โ Returns a stringified version of the object.$dt->is_leap_year โ Returns a boolean indicating whether or not the datetime is in a leap year.$dt->is_last_day_of_month โ Returns a boolean.$dt->is_last_day_of_quarter โ Returns a boolean.$dt->is_last_day_of_year โ Returns a boolean.$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 โ Returns ($week_year, $week_number).$dt->week_year โ Returns the year of the week.$dt->week_number โ Returns the week of the year, from 1..53.$dt->week_of_month โ The week of the month, from 0..5.$dt->jd, $dt->mjd โ Returns the Julian Day and Modified Julian Day.$dt->time_zone โ Returns the DateTime::TimeZone object.$dt->offset โ Returns the offset from UTC, in seconds.$dt->is_dst โ Returns a boolean indicating DST.$dt->time_zone_long_name โ Shortcut for $dt->time_zone->name.$dt->time_zone_short_name โ Returns the time zone abbreviation (e.g., "PST").$dt->strftime( $format, ... ) โ Implements strftime.$dt->format_cldr( $format, ... ) โ Implements CLDR date formatting.$dt->epoch โ Returns the UTC epoch value (integer seconds).$dt->is_finite, $dt->is_infinite โ Distinguish normal from infinite datetimes.$dt->utc_rd_values โ Returns UTC Rata Die days, seconds, and nanoseconds.$dt->leap_seconds โ Returns the number of leap seconds up to the datetime.$dt->locale โ Returns the datetime's DateTime::Locale object.$dt->formatter โ Returns the current formatter object or class.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.
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.
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.
You can override "CORE::GLOBAL::time" before loading DateTime, or override "DateTime::_core_time":
no warnings 'redefine';
local *DateTime::_core_time = sub { return 42 };
$dt->delta_days for date-only math.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.
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.
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.
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.
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.
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.
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.
The CLDR pattern language is more powerful and complex than strftime. Patterns are simply letters without any prefix. Surround literal text with single quotes ('').
G{1,3} โ The abbreviated era (BC, AD).GGGG โ The wide era (Before Christ, Anno Domini).y and y{3,} โ The year, zero-prefixed as needed.yy โ A special case that always produces a two-digit year.Y{1,} โ The year in "week of the year" calendars.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.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.w{1,2} โ The week of the year.W โ The week of the 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.g{1,} โ The modified Julian day.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.e{1,2} โ The local numeric day of the week.c โ The numeric day of the week from 1 to 7, Monday is 1.a โ The localized form of AM or PM.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 locale.m{1,2} โ The minute.s{1,2} โ The second.S{1,} โ The fractional portion of the seconds.A{1,} โ The millisecond of the day.z{1,3} โ The time zone short name.zzzz โ The time zone long name.Z{1,3} โ The time zone offset.ZZZZZ โ The time zone offset as a sexagesimal number (e.g., "-05:00").%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.%d โ The day of the month as a decimal number (01-31).%D โ Equivalent to %m/%d/%y.%e โ Like %d, but a leading zero is replaced by a space.%F โ Equivalent to %Y-%m-%d.%G โ The ISO 8601 year with century.%g โ Like %G, but without century.%H โ The hour as a decimal number using a 24-hour clock (00-23).%I โ The hour as a decimal number using a 12-hour clock (01-12).%j โ The day of the year as a decimal number (001-366).%m โ The month as a decimal number (01-12).%M โ The minute as a decimal number (00-59).%n โ A newline character.%N โ The fractional seconds digits.%p โ Either `AM' or `PM'.%P โ Like %p but in lowercase.%r โ The time in a.m. or p.m. notation.%R โ The time in 24-hour notation.%s โ The number of seconds since the epoch.%S โ The second as a decimal number (00-61).%t โ A tab character.%T โ The time in 24-hour notation.%u โ The day of the week as a decimal, Monday being 1.%U โ The week number of the current year.%V โ The ISO 8601 week number.%w โ The day of the week as a decimal, Sunday being 0.%W โ The week number of the current year.%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.%Y โ The year as a decimal number including the century.%z โ The time-zone as hour offset from UTC.%Z โ The time zone abbreviation.%% โ A literal `%' character.%{method} โ Any method name."DateTime" implements Storable hooks in order to reduce the size of a serialized "DateTime" object.
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.
This module is part of a larger ecosystem of modules in the DateTime family.
Parse and format datetimes. All start with DateTime::Format::.
Implement non-Gregorian calendars. All start with DateTime::Calendar::.
Calculate dates for events. All start with DateTime::Event::.
Many other modules work with DateTime, including modules in the DateTimeX namespace.
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.
A Date with Perl (presentation). datetime AT perl.org mailing list.
Bugs may be submitted at GitHub. There is a mailing list available for users of this distribution.
The source code repository for DateTime can be found at GitHub.
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.
Dave Rolsky
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
This software is Copyright (c) 2003 - 2021 by Dave Rolsky. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible).
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)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format