DateTime
view release on metacpan or search on metacpan
lib/DateTime.pm view on Meta::CPAN
}
}
sub now {
my $class = shift;
return $class->from_epoch( epoch => $class->_core_time, @_ );
}
sub _maybe_future_dst_warning {
shift;
my $year = shift;
my $tz = shift;
return unless $year >= 5000 && $tz;
my $tz_name = ref $tz ? $tz->name : $tz;
return if $tz_name eq 'floating' || $tz_name eq 'UTC';
warnings::warnif(
"You are creating a DateTime object with a far future year ($year) and a time zone ($tz_name)."
. ' If the time zone you specified has future DST changes this will be very slow.'
);
}
# use scalar time in case someone's loaded Time::Piece
sub _core_time {
return scalar time;
}
sub today { shift->now(@_)->truncate( to => 'day' ) }
{
my $validator = validation_for(
name => '_check_from_object_params',
name_is_optional => 1,
params => {
object => { type => t('ConvertibleObject') },
locale => {
type => t('Locale'),
optional => 1,
},
formatter => {
type => t('Formatter'),
optional => 1,
},
},
);
sub from_object {
my $class = shift;
my %p = $validator->(@_);
my $object = delete $p{object};
if ( $object->isa('DateTime::Infinite') ) {
return $object->clone;
}
my ( $rd_days, $rd_secs, $rd_nanosecs ) = $object->utc_rd_values;
# A kludge because until all calendars are updated to return all
# three values, $rd_nanosecs could be undef
$rd_nanosecs ||= 0;
# This is a big hack to let _seconds_as_components operate naively
# on the given value. If the object _is_ on a leap second, we'll
# add that to the generated seconds value later.
my $leap_seconds = 0;
if ( $object->can('time_zone')
&& !$object->time_zone->is_floating
&& $rd_secs > 86399
&& $rd_secs <= $class->_day_length($rd_days) ) {
$leap_seconds = $rd_secs - 86399;
$rd_secs -= $leap_seconds;
}
my %args;
@args{qw( year month day )} = $class->_rd2ymd($rd_days);
@args{qw( hour minute second )}
= $class->_seconds_as_components($rd_secs);
$args{nanosecond} = $rd_nanosecs;
$args{second} += $leap_seconds;
my $new = $class->new( %p, %args, time_zone => 'UTC' );
if ( $object->can('time_zone') ) {
$new->set_time_zone( $object->time_zone );
}
else {
$new->set_time_zone( $class->_default_time_zone );
}
return $new;
}
}
{
my $validator = validation_for(
name => '_check_last_day_of_month_params',
name_is_optional => 1,
params => {
year => { type => t('Year') },
month => { type => t('Month') },
day => {
type => t('DayOfMonth'),
default => 1,
},
hour => {
type => t('Hour'),
default => 0,
},
minute => {
type => t('Minute'),
default => 0,
},
second => {
type => t('Second'),
default => 0,
},
nanosecond => {
lib/DateTime.pm view on Meta::CPAN
$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);
=head1 DESCRIPTION
DateTime is a class for the representation of date/time combinations, and is
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 differs from how
dates are often written using "BCE/CE" or "BC/AD".
For infinite datetimes, please see the L<DateTime::Infinite|DateTime::Infinite>
module.
=head1 USAGE
=head2 0-based Versus 1-based Numbers
The C<DateTime> module follows a simple logic for determining whether or not a
given number is 0-based or 1-based.
Month, day of month, day of week, and day of year are 1-based. Any method that
is 1-based also has an equivalent 0-based method ending in C<_0>. So for
example, this class provides both C<day_of_week> and C<day_of_week_0> methods.
The C<day_of_week_0> method still treats Monday as the first day of the week.
All I<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 I<is> a year 0.
There is no C<quarter_0> method.
=head2 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 C<set>, or methods that take parameters. Methods that retrieve information
about the object, such as C<year> or C<epoch>, will never die.
=head2 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 C<"en-US"> is used.
=head2 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 B<do not> mix these with floating datetimes.
=head2 Math
If you are going to be doing date math, please read the section L<How DateTime
Math Works>.
=head2 Determining the Local Time Zone Can Be Slow
lib/DateTime.pm view on Meta::CPAN
=head3 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 C<new> method, it accepts
C<time_zone>, C<locale>, and C<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 C<time_zone>, then this time zone will be applied I<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
=head3 DateTime->now( ... )
This class method is equivalent to calling C<from_epoch> with the value
returned from Perl's C<time> function. Just as with the C<new> method, it
accepts C<time_zone> and C<locale> parameters.
By default, the returned object will be in the UTC time zone.
If you want sub-second resolution, use the L<DateTime::HiRes> module's C<<
DateTime::HiRes->now >> method instead.
=head3 DateTime->today( ... )
This class method is equivalent to:
DateTime->now(@_)->truncate( to => 'day' );
=head3 DateTime->last_day_of_month( ... )
This constructor takes the same arguments as can be given to the C<new> method,
except for C<day>. Additionally, both C<year> and C<month> are required.
=head3 DateTime->from_day_of_year( ... )
This constructor takes the same arguments as can be given to the C<new> method,
except that it does not accept a C<month> or C<day> argument. Instead, it
requires both C<year> and C<day_of_year>. The day of year must be between 1 and
366, and 366 is only allowed for leap years.
=head3 DateTime->from_object( object => $object, ... )
This class method can be used to construct a new DateTime object from any
object that implements the C<utc_rd_values> method. All C<DateTime::Calendar>
modules must implement this method in order to provide cross-calendar
compatibility. This method accepts a C<locale> and C<formatter> parameter
If the object passed to this method has a C<time_zone> method, that is used to
set the time zone of the newly created C<DateTime> object.
Otherwise, the returned object will be in the floating time zone.
=head3 $dt->clone
This object method returns a new object that is replica of the object upon
which the method is called.
=head2 "Get" Methods
This class has many methods for retrieving information about an object.
=head3 $dt->year
Returns the year.
=head3 $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".
=head3 $dt->era_name
Returns the long name of the current era, something like "Before Christ". See
the L</Locales> section for more details.
=head3 $dt->era_abbr
Returns the abbreviated name of the current era, something like "BC". See the
L</Locales> section for more details.
=head3 $dt->christian_era
Returns a string, either "BC" or "AD", according to the year.
=head3 $dt->secular_era
Returns a string, either "BCE" or "CE", according to the year.
=head3 $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 C<ce_year>, so that year 1 is "1" and year 0 is "1BC". See the L</Locales>
section for more details.
=head3 $dt->year_with_christian_era
Like C<year_with_era>, but uses the C<christian_era> method to get the era
name.
=head3 $dt->year_with_secular_era
Like C<year_with_era>, but uses the C<secular_era> method to get the era name.
=head3 $dt->month
lib/DateTime.pm view on Meta::CPAN
This method is also available as C<< $dt->iso8601 >>, but it's not really a
very good ISO8601 format, as it lacks a time zone. If called as C<<
$dt->iso8601 >> you cannot change the separator, as ISO8601 specifies that "T"
must be used to separate them.
=head3 $dt->rfc3339
This formats a datetime in RFC3339 format. This is the same as C<<
$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.
=head3 $dt->stringify
This method returns a stringified version of the object. It is also how
stringification overloading is implemented. If the object has a formatter, then
its C<format_datetime> method is used to produce a string. Otherwise, this
method calls C<< $dt->iso8601 >> to produce a string. See L</Formatters And
Stringification> for details.
=head3 $dt->is_leap_year
This method returns a boolean value indicating whether or not the datetime
object is in a leap year.
=head3 $dt->is_last_day_of_month
This method returns a boolean value indicating whether or not the datetime
object is the last day of the month.
=head3 $dt->is_last_day_of_quarter
This method returns a boolean value indicating whether or not the datetime
object is the last day of the quarter.
=head3 $dt->is_last_day_of_year
This method returns a boolean value indicating whether or not the datetime
object is the last day of the year.
=head3 $dt->month_length
This method returns the number of days in the current month.
=head3 $dt->quarter_length
This method returns the number of days in the current quarter.
=head3 $dt->year_length
This method returns the number of days in the current year.
=head3 $dt->week
my ( $week_year, $week_number ) = $dt->week;
Returns information about the calendar week for the date. The values returned
by this method are also available separately through the C<< $dt->week_year >>
and C<< $dt->week_number >> methods.
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 that it's the first week
to overlap the new year by at least four days.
Typically the week year will be the same as the year that the object is in, but
dates at the very beginning of a calendar year often end up in the last week of
the prior year, and similarly, the final few days of the year may be placed in
the first week of the next year.
=head3 $dt->week_year
Returns the year of the week. See C<< $dt->week >> for details.
=head3 $dt->week_number
Returns the week of the year, from 1..53. See C<< $dt->week >> for details.
=head3 $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 correlates to the ISO8601 week of year definition. A day in the week
I<before> the week with the first Thursday will be week 0.
=head3 $dt->jd, $dt->mjd
These return the Julian Day and Modified Julian Day, respectively. The value
returned is a floating point number. The fractional portion of the 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".
=head3 $dt->time_zone
This returns the L<DateTime::TimeZone> object for the datetime object.
=head3 $dt->offset
This returns the offset from UTC, in seconds, of the datetime object's time
zone.
=head3 $dt->is_dst
Returns a boolean indicating whether or not the datetime's time zone is
currently in Daylight Saving Time or not.
=head3 $dt->time_zone_long_name
This is a shortcut for C<< $dt->time_zone->name >>. It's provided so that one
can use "%{time_zone_long_name}" as a strftime format specifier.
=head3 $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 B<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.
=head3 $dt->strftime( $format, ... )
This method implements functionality similar to the C<strftime> method in C.
However, if given multiple format strings, then it will return multiple
scalars, one for each format string.
See the L<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.
Note that any deviation from the POSIX standard is probably a bug. DateTime
should match the output of C<POSIX::strftime> for any given pattern.
=head3 $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 L<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.
=head3 $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.
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.
=head3 $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 C<Time::HiRes> module.
Note that 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.
my $dt = DateTime->new( year => 2012, nanosecond => 4 );
say $dt->hires_epoch;
On my system, this simply prints C<1325376000> because adding C<0.000000004> to
C<1325376000> returns C<1325376000>.
=head3 $dt->is_finite, $dt->is_infinite
These methods allow you to distinguish normal datetime objects from infinite
ones. Infinite datetime objects are documented in L<DateTime::Infinite>.
=head3 $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.
=head3 $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 L<DateTime::Event::Recurrence>.
=head3 $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.
=head3 $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.
=head3 $dt->locale
Returns the datetime's L<DateTime::Locale> object.
=head3 $dt->formatter
Returns the current formatter object or class. See L<Formatters And
Stringification> for details.
=head2 "Set" Methods
The remaining methods provided by C<DateTime>, except where otherwise
specified, return the object itself, thus making method chaining possible. For
example:
my $dt = DateTime->now->set_time_zone( 'Australia/Sydney' );
my $first = DateTime
->last_day_of_month( year => 2003, month => 3 )
->add( days => 1 )
->subtract( seconds => 1 );
=head3 $dt->set( .. )
This method can be used to change the local components of a date time. This
method accepts any parameter allowed by the C<new> method except for C<locale>
or C<time_zone>. Use C<set_locale> and C<set_time_zone> for those instead.
This method performs parameter validation just like the C<new> method.
B<Do not use this method to do date math. Use the C<add> and C<subtract>
methods instead.>
=head3 $dt->set_year, $dt->set_month, etc.
DateTime has a C<set_*> method for every item that can be passed to the
constructor:
=over 4
=item * $dt->set_year
lib/DateTime.pm view on Meta::CPAN
This method returns a new L<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 larger than a second do not represent a fixed number of seconds.
Note that because of leap seconds, this may not return the same result as doing
this math based on the value returned by C<< $dt->epoch >>.
=head3 $dt->is_between( $lower, $upper )
Checks whether C<$dt> is strictly between two other DateTime objects.
"Strictly" means that C<$dt> must be greater than C<$lower> and less than
C<$upper>. If it is I<equal> to either object then this method returns false.
=head2 Class Methods
=head3 DateTime->DefaultLocale($locale)
This can be used to specify the default locale to be used when creating
DateTime objects. If unset, then C<"en-US"> is used.
This exists for backwards compatibility, but is probably best avoided. This
will change the default locale for every C<DateTime> object created in your
application, even those created by third party libraries which also use
C<DateTime>.
=head3 DateTime->compare( $dt1, $dt2 ), DateTime->compare_ignore_floating( $dt1, $dt2 )
$cmp = DateTime->compare( $dt1, $dt2 );
$cmp = DateTime->compare_ignore_floating( $dt1, $dt2 );
This method compare two DateTime objects. The semantics are compatible with
Perl's C<sort> function; it returns C<-1> if C<< $dt1 < $dt2 >>, C<0> if C<$dt1
== $dt2>, C<1> if C<< $dt1 > $dt2 >>.
If one of the two DateTime objects has a floating time zone, it will first be
converted to the time zone of the other object. This is what you want most of
the time, but it can lead to inconsistent results when you compare a number of
DateTime objects, some of which are floating, and some of which are in other
time zones.
If you want to have consistent results (because you want to sort an array of
objects, for example), you can use the C<compare_ignore_floating> method:
@dates = sort { DateTime->compare_ignore_floating( $a, $b ) } @dates;
In this case, objects with a floating time zone will be sorted as if they were
UTC times.
Since DateTime objects overload comparison operators, this:
@dates = sort @dates;
is equivalent to this:
@dates = sort { DateTime->compare( $a, $b ) } @dates;
DateTime objects can be compared to any other calendar class that implements
the C<utc_rd_values> method.
=head2 Testing Code That Uses DateTime
If you are trying to test code that calls uses DateTime, you may want to be to
explicitly set the value returned by Perl's C<time> builtin. This builtin is
called by C<< DateTime->now >> and C<< DateTime->today >>.
You can override C<CORE::GLOBAL::time>, but this will only work if you do this
B<before> loading DateTime. If doing this is inconvenient, you can also
override C<DateTime::_core_time>:
no warnings 'redefine';
local *DateTime::_core_time = sub { return 42 };
DateTime is guaranteed to call this subroutine to get the current C<time>
value. You can also override the C<_core_time> sub in a subclass of DateTime
and use that.
=head2 How DateTime Math Works
It's important to have some understanding of how datetime math is implemented
in order to effectively use this module and L<DateTime::Duration>.
=head3 Making Things Simple
If you want to simplify your life and not have to think too hard about the
nitty-gritty of datetime math, I have several recommendations:
=over 4
=item * use the floating time zone
If you do not 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.
Note that in most cases you will want to start by creating an object in a
specific zone and I<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');
=item * 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;
=item * 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 C<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
L<Leap Seconds and Date Math>
=item * date vs datetime math
If you only care about the date (calendar) portion of a datetime, you should
use either C<< $dt->delta_md >> or C<< $dt->delta_days >>, not C<<
$dt->subtract_datetime >>. This will give predictable, unsurprising results,
free from DST-related complications.
=item * $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 that the following formulas are always true:
$dt2 - $dt1 = $dur
$dt1 + $dur = $dt2
$dt2 - $dur = $dt1
Note that using C<< $dt->delta_days >> ensures that this formula always works,
regardless of the time zones of the objects involved, as does using C<<
$dt->subtract_datetime_absolute >>. Other methods of subtraction are not always
reversible.
=item * 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 C<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.
=back
=head3 Adding a Duration to a DateTime
The parts of a duration can be broken down into five parts. These are months,
days, minutes, seconds, and nanoseconds. Adding one month to a date is
different than adding 4 weeks or 28, 29, 30, or 31 days. Similarly, due to DST
and leap seconds, adding a day can be different than adding 86,400 seconds, and
adding a minute is not exactly the same as 60 seconds.
We cannot convert between these units, except for seconds and nanoseconds,
because there is no fixed conversion between most pairs of units. That is
because of things like leap seconds, DST changes, etc.
C<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. For the days and months the local (not UTC) values are
used. For minutes and seconds, the local values are used. This generally just
works.
This means that adding one month and one day to February 28, 2003 will produce
the date April 1, 2003, not March 29, 2003.
my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
$dt->add( months => 1, days => 1 );
# 2003-04-01 - the result
On the other hand, if we add months first, and then separately add days, we end
up with March 29, 2003:
$dt->add( months => 1 )->add( days => 1 );
# 2003-03-29
lib/DateTime.pm view on Meta::CPAN
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 C<$dt2>
in the above example still leaves the clock time at "01:00:00". This time we
are accounting for a 25 hour day.
=head3 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 C<< $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 C<< $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 C<< $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 C<$dt1>.
This can be facilitated by the L<DateTime::Duration> class's C<<
$dur->calendar_duration >> and C<< $dur->clock_duration >> methods:
$dt2->subtract_duration( $dur->clock_duration )
->subtract_duration( $dur->calendar_duration );
=head3 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.
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
lib/DateTime.pm view on Meta::CPAN
$a cmp $b } @dates>.
The module also overloads stringification using the object's formatter,
defaulting to C<iso8601> method. See L<Formatters And Stringification> for
details.
=head2 Formatters And Stringification
You can optionally specify a C<formatter>, which is usually a
C<DateTime::Format::*> object or class, to control the stringification of the
DateTime object.
Any of the constructor methods can accept a formatter argument:
my $formatter = DateTime::Format::Strptime->new(...);
my $dt = DateTime->new( year => 2004, formatter => $formatter );
Or, you can set it afterwards:
$dt->set_formatter($formatter);
$formatter = $dt->formatter;
Once you set the formatter, the overloaded stringification method will use the
formatter. If unspecified, the C<iso8601> method is used.
A formatter can be handy when you know that in your application you want to
stringify your DateTime objects into a special format all the time, for example
in Postgres format.
If you provide a formatter class name or object, it must implement a
C<format_datetime> method. This method will be called with just the C<DateTime>
object as its argument.
=head2 CLDR Patterns
The CLDR pattern language is both more powerful and more complex than strftime.
Unlike strftime patterns, you often have to explicitly escape text that you do
not want formatted, as the patterns are simply letters without any prefix.
For example, C<"yyyy-MM-dd"> is a valid CLDR pattern. If you want to include
any lower or upper case ASCII characters as-is, you can surround them with
single quotes ('). If you want to include a single quote, you must escape it as
two single quotes ('').
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.
Many CLDR patterns which produce numbers will pad the number with leading
zeroes depending on the length of the format specifier. For example, C<"h">
represents the current hour from 1-12. If you specify C<"hh"> then hours 1-9
will have a leading zero prepended.
However, CLDR often uses five of a letter to represent the narrow form of a
pattern. This inconsistency is necessary for backwards compatibility.
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.
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.
CLDR provides a fairly complex system for localizing time zones that we ignore
entirely. The time zone patterns just use the information provided by
C<DateTime::TimeZone>, and I<do not follow the CLDR spec>.
The output of a CLDR pattern is always localized, when applicable.
CLDR provides the following patterns:
=over 4
=item * G{1,3}
The abbreviated era (BC, AD).
=item * GGGG
The wide era (Before Christ, Anno Domini).
=item * GGGGG
The narrow era, if it exists (but it mostly doesn't).
=item * 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".
=item * 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.
=item * Y{1,}
The year in "week of the year" calendars, from C<< $dt->week_year >>.
=item * u{1,}
Same as "y" except that "uu" is not a special case.
=item * Q{1,2}
The quarter as a number (1..4).
=item * QQQ
The abbreviated format form for the quarter.
=item * QQQQ
The wide format form for the quarter.
=item * q{1,2}
The quarter as a number (1..4).
=item * qqq
The abbreviated stand-alone form for the quarter.
=item * qqqq
The wide stand-alone form for the quarter.
=item * M{1,2}
The numerical month.
=item * MMM
The abbreviated format form for the month.
=item * MMMM
The wide format form for the month.
=item * MMMMM
The narrow format form for the month.
=item * L{1,2}
The numerical month.
=item * LLL
The abbreviated stand-alone form for the month.
=item * LLLL
The wide stand-alone form for the month.
=item * LLLLL
The narrow stand-alone form for the month.
lib/DateTime.pm view on Meta::CPAN
=item * %%
A literal `%' character.
=item * %{method}
Any method name may be specified using the format C<%{method}> name where
"method" is a valid C<DateTime> object method.
=back
=head2 DateTime and Storable
C<DateTime> implements L<Storable> hooks in order to reduce the size of a
serialized C<DateTime> object.
=head1 DEVELOPMENT TOOLS
If you're working on the C<DateTIme> code base, there are a few extra non-Perl
tools that you may find useful, notably
L<precious|https://github.com/houseabsolute/precious>, a meta-linter/tidier.
You can install all the necessary tools in C<$HOME/bin> by running
F<./dev-bin/install-dev-tools.sh>.
Try running C<precious tidy -a> to tidy all the tidyable files in the repo, and
C<precious lint -a> to run all the lint checks.
You can enable a git pre-commit hook for linting by running F<./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.
=head1 THE DATETIME PROJECT ECOSYSTEM
This module is part of a larger ecosystem of modules in the DateTime family.
=head2 L<DateTime::Set>
The L<DateTime::Set> module represents sets (including recurrences) of
datetimes. Many modules return sets or recurrences.
=head2 Format Modules
The various format modules exist to parse and format datetimes. For example,
L<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 C<formatter> with a DateTime
object.
All format modules start with
L<DateTime::Format::|https://metacpan.org/search?q=datetime%3A%3Aformat>.
=head2 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
L<DateTime::Calendar::|https://metacpan.org/search?q=datetime%3A%3Acalendar>.
=head2 Event Modules
There are a number of modules that calculate the dates for events, such as
Easter, Sunrise, etc.
All event modules start with
L<DateTime::Event::|https://metacpan.org/search?q=datetime%3A%3Aevent>.
=head2 Others
There are many other modules that work with DateTime, including modules in the
L<DateTimeX namespace|https://metacpan.org/search?q=datetimex> namespace, as
well as others.
See L<MetaCPAN|https://metacpan.org/search?q=datetime> for more modules.
=head1 KNOWN BUGS
The tests in F<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.
=head1 SEE ALSO
L<A Date with Perl|http://presentations.houseabsolute.com/a-date-with-perl/> -
a talk I've given at a few YAPCs.
L<datetime@perl.org mailing list|http://lists.perl.org/list/datetime.html>
=head1 SUPPORT
Bugs may be submitted at L<https://github.com/houseabsolute/DateTime.pm/issues>.
There is a mailing list available for users of this distribution,
L<mailto:datetime@perl.org>.
=head1 SOURCE
The source code repository for DateTime can be found at L<https://github.com/houseabsolute/DateTime.pm>.
=head1 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 B<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 L<https://houseabsolute.com/foss-donations/>.
( run in 1.258 second using v1.01-cache-2.11-cpan-39bf76dae61 )