18 unless ( $ENV{PERL_DATETIME_PP} )
24 XSLoader::load( 'DateTime', $DateTime::VERSION );
26 $DateTime::IsPurePerl = 0;
29 die $@ if $@ && $@ !~ /object version|loadable object/;
31 $loaded = 1 unless $@;
36 require DateTimePPExtra
37 unless defined &DateTime::_normalize_tai_seconds;
45 use DateTime::Duration;
46 use DateTime::Locale 0.40;
47 use DateTime::TimeZone 0.59;
48 use Time::Local qw( timegm_nocheck );
49 use Params::Validate qw( validate validate_pos SCALAR BOOLEAN HASHREF OBJECT );
51 # for some reason, overloading doesn't work unless fallback is listed
54 # 3rd parameter ( $_[2] ) means the parameters are 'reversed'.
55 # see: "Calling conventions for binary operations" in overload docs.
57 use overload ( 'fallback' => 1,
58 '<=>' => '_compare_overload',
59 'cmp' => '_compare_overload',
61 '-' => '_subtract_overload',
62 '+' => '_add_overload',
63 'eq' => '_string_equals_overload',
64 'ne' => '_string_not_equals_overload',
67 # Have to load this after overloading is defined, after BEGIN blocks
68 # or else weird crashes ensue
69 require DateTime::Infinite;
71 use constant MAX_NANOSECONDS => 1_000_000_000; # 1E9 = almost 32 bits
73 use constant INFINITY => (9 ** 9 ** 9);
74 use constant NEG_INFINITY => -1 * (9 ** 9 ** 9);
75 use constant NAN => INFINITY - INFINITY;
77 use constant SECONDS_PER_DAY => 86400;
79 use constant duration_class => 'DateTime::Duration';
81 my( @MonthLengths, @LeapYearMonthLengths );
86 ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
88 @LeapYearMonthLengths = @MonthLengths;
89 $LeapYearMonthLengths[1]++;
93 # I'd rather use Class::Data::Inheritable for this, but there's no
94 # way to add the module-loading behavior to an accessor it
95 # creates, despite what its docs say!
105 DateTime::Locale->load($lang);
107 $DefaultLocale = $lang;
110 return $DefaultLocale;
113 *DefaultLanguage = \&DefaultLocale;
115 __PACKAGE__->DefaultLocale('en_US');
118 { year => { type => SCALAR,
121 sub { $_[0] =~ /^-?\d+$/ }
124 month => { type => SCALAR, default => 1,
126 { 'an integer between 1 and 12' =>
127 sub { $_[0] =~ /^\d+$/ && $_[0] >= 1 && $_[0] <= 12 }
130 day => { type => SCALAR, default => 1,
132 { 'an integer which is a possible valid day of month' =>
133 sub { $_[0] =~ /^\d+$/ && $_[0] >= 1 && $_[0] <= 31 }
136 hour => { type => SCALAR, default => 0,
138 { 'an integer between 0 and 23' =>
139 sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 && $_[0] <= 23 },
142 minute => { type => SCALAR, default => 0,
144 { 'an integer between 0 and 59' =>
145 sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 && $_[0] <= 59 },
148 second => { type => SCALAR, default => 0,
150 { 'an integer between 0 and 61' =>
151 sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 && $_[0] <= 61 },
154 nanosecond => { type => SCALAR, default => 0,
156 { 'a positive integer' =>
157 sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 },
160 locale => { type => SCALAR | OBJECT,
162 language => { type => SCALAR | OBJECT,
168 time_zone => { type => SCALAR | OBJECT,
169 default => 'floating' },
170 formatter => { type => SCALAR | OBJECT, can => 'format_datetime', optional => 1 },
176 my %p = validate( @_, $NewValidate );
178 Carp::croak( "Invalid day of month (day = $p{day} - month = $p{month} - year = $p{year})\n" )
179 if $p{day} > $class->_month_length( $p{year}, $p{month} );
181 my $self = bless {}, $class;
183 $p{locale} = delete $p{language} if exists $p{language};
184 $p{locale} = $class->DefaultLocale unless defined $p{locale};
186 if ( ref $p{locale} )
188 $self->{locale} = $p{locale};
192 $self->{locale} = DateTime::Locale->load( $p{locale} );
196 ( ref $p{time_zone} ?
198 DateTime::TimeZone->new( name => $p{time_zone} )
201 $self->{local_rd_days} =
202 $class->_ymd2rd( @p{ qw( year month day ) } );
204 $self->{local_rd_secs} =
205 $class->_time_as_seconds( @p{ qw( hour minute second ) } );
207 $self->{offset_modifier} = 0;
209 $self->{rd_nanosecs} = $p{nanosecond};
210 $self->{formatter} = $p{formatter};
212 $self->_normalize_nanoseconds( $self->{local_rd_secs}, $self->{rd_nanosecs} );
214 # Set this explicitly since it can't be calculated accurately
215 # without knowing our time zone offset, and it's possible that the
216 # offset can't be calculated without having at least a rough guess
217 # of the datetime's year. This year need not be correct, as long
218 # as its equal or greater to the correct number, so we fudge by
219 # adding one to the local year given to the constructor.
220 $self->{utc_year} = $p{year} + 1;
224 $self->_handle_offset_modifier( $p{second} );
226 $self->_calc_local_rd;
228 if ( $p{second} > 59 )
230 if ( $self->{tz}->is_floating ||
231 # If true, this means that the actual calculated leap
232 # second does not occur in the second given to new()
233 ( $self->{utc_rd_secs} - 86399
238 Carp::croak( "Invalid second value ($p{second})\n" );
245 # This method exists for the benefit of internal methods which create
246 # a new object based on the current object, like set() and truncate().
251 my %old = map { $_ => $self->$_() }
252 qw( year month day hour minute second nanosecond
254 $old{formatter} = $self->formatter()
255 if defined $self->formatter();
257 return (ref $self)->new( %old, @_ );
260 sub _handle_offset_modifier
264 $self->{offset_modifier} = 0;
266 return if $self->{tz}->is_floating;
269 my $utc_is_valid = shift;
271 my $utc_rd_days = $self->{utc_rd_days};
273 my $offset = $utc_is_valid ? $self->offset : $self->_offset_for_local_datetime;
276 && $self->{local_rd_secs} >= $offset
279 if ( $second < 60 && $offset > 0 )
281 $self->{offset_modifier} =
282 $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
284 $self->{local_rd_secs} += $self->{offset_modifier};
286 elsif ( $second == 60
288 ( ( $self->{local_rd_secs} == $offset
292 && $self->{local_rd_secs} > 86399 ) )
295 my $mod = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
299 $self->{utc_rd_secs} -= $mod;
301 $self->_normalize_seconds;
306 && $self->{local_rd_secs} >= SECONDS_PER_DAY + $offset )
310 $self->{offset_modifier} =
311 $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
313 $self->{local_rd_secs} += $self->{offset_modifier};
315 elsif ( $second == 60 && $self->{local_rd_secs} == SECONDS_PER_DAY + $offset )
317 my $mod = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
321 $self->{utc_rd_secs} -= $mod;
323 $self->_normalize_seconds;
333 delete $self->{utc_c};
335 if ( $self->{tz}->is_utc || $self->{tz}->is_floating )
337 $self->{utc_rd_days} = $self->{local_rd_days};
338 $self->{utc_rd_secs} = $self->{local_rd_secs};
342 my $offset = $self->_offset_for_local_datetime;
344 $offset += $self->{offset_modifier};
346 $self->{utc_rd_days} = $self->{local_rd_days};
347 $self->{utc_rd_secs} = $self->{local_rd_secs} - $offset;
350 # We account for leap seconds in the new() method and nowhere else
352 $self->_normalize_tai_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} );
355 sub _normalize_seconds
359 return if $self->{utc_rd_secs} >= 0 && $self->{utc_rd_secs} <= 86399;
361 if ( $self->{tz}->is_floating )
363 $self->_normalize_tai_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} );
367 $self->_normalize_leap_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} );
375 delete $self->{local_c};
377 # We must short circuit for UTC times or else we could end up with
378 # loops between DateTime.pm and DateTime::TimeZone
379 if ( $self->{tz}->is_utc || $self->{tz}->is_floating )
381 $self->{local_rd_days} = $self->{utc_rd_days};
382 $self->{local_rd_secs} = $self->{utc_rd_secs};
386 my $offset = $self->offset;
388 $self->{local_rd_days} = $self->{utc_rd_days};
389 $self->{local_rd_secs} = $self->{utc_rd_secs} + $offset;
391 # intentionally ignore leap seconds here
392 $self->_normalize_tai_seconds( $self->{local_rd_days}, $self->{local_rd_secs} );
394 $self->{local_rd_secs} += $self->{offset_modifier};
397 $self->_calc_local_components;
400 sub _calc_local_components
404 @{ $self->{local_c} }{ qw( year month day day_of_week
405 day_of_year quarter day_of_quarter) } =
406 $self->_rd2ymd( $self->{local_rd_days}, 1 );
408 @{ $self->{local_c} }{ qw( hour minute second ) } =
409 $self->_seconds_as_components
410 ( $self->{local_rd_secs}, $self->{utc_rd_secs}, $self->{offset_modifier} );
413 sub _calc_utc_components
417 die "Cannot get UTC components before UTC RD has been calculated\n"
418 unless defined $self->{utc_rd_days};
420 @{ $self->{utc_c} }{ qw( year month day ) } =
421 $self->_rd2ymd( $self->{utc_rd_days} );
423 @{ $self->{utc_c} }{ qw( hour minute second ) } =
424 $self->_seconds_as_components( $self->{utc_rd_secs} );
431 $self->_calc_utc_components unless exists $self->{utc_c}{year};
433 return @{ $self->{utc_c} }{ qw( year month day ) };
440 $self->_calc_utc_components unless exists $self->{utc_c}{hour};
442 return @{ $self->{utc_c} }{ qw( hour minute second ) };
446 my $spec = { epoch => { regex => qr/^-?(?:\d+(?:\.\d*)?|\.\d+)$/ },
447 locale => { type => SCALAR | OBJECT, optional => 1 },
448 language => { type => SCALAR | OBJECT, optional => 1 },
449 time_zone => { type => SCALAR | OBJECT, optional => 1 },
450 formatter => { type => SCALAR | OBJECT, can => 'format_datetime',
457 my %p = validate( @_, $spec );
461 # Because epoch may come from Time::HiRes
462 my $fraction = $p{epoch} - int( $p{epoch} );
463 $args{nanosecond} = int( $fraction * MAX_NANOSECONDS )
466 # Note, for very large negative values this may give a
467 # blatantly wrong answer.
468 @args{ qw( second minute hour day month year ) } =
469 ( gmtime( int delete $p{epoch} ) )[ 0..5 ];
473 my $self = $class->new( %p, %args, time_zone => 'UTC' );
475 $self->set_time_zone( $p{time_zone} ) if exists $p{time_zone};
481 # use scalar time in case someone's loaded Time::Piece
482 sub now { shift->from_epoch( epoch => (scalar time), @_ ) }
484 sub today { shift->now(@_)->truncate( to => 'day' ) }
487 my $spec = { object => { type => OBJECT,
488 can => 'utc_rd_values',
490 locale => { type => SCALAR | OBJECT, optional => 1 },
491 language => { type => SCALAR | OBJECT, optional => 1 },
492 formatter => { type => SCALAR | OBJECT, can => 'format_datetime',
499 my %p = validate( @_, $spec );
501 my $object = delete $p{object};
503 my ( $rd_days, $rd_secs, $rd_nanosecs ) = $object->utc_rd_values;
505 # A kludge because until all calendars are updated to return all
506 # three values, $rd_nanosecs could be undef
509 # This is a big hack to let _seconds_as_components operate naively
510 # on the given value. If the object _is_ on a leap second, we'll
511 # add that to the generated seconds value later.
512 my $leap_seconds = 0;
513 if ( $object->can('time_zone') && ! $object->time_zone->is_floating
514 && $rd_secs > 86399 && $rd_secs <= $class->_day_length($rd_days) )
516 $leap_seconds = $rd_secs - 86399;
517 $rd_secs -= $leap_seconds;
521 @args{ qw( year month day ) } = $class->_rd2ymd($rd_days);
522 @args{ qw( hour minute second ) } =
523 $class->_seconds_as_components($rd_secs);
524 $args{nanosecond} = $rd_nanosecs;
526 $args{second} += $leap_seconds;
528 my $new = $class->new( %p, %args, time_zone => 'UTC' );
530 if ( $object->can('time_zone') )
532 $new->set_time_zone( $object->time_zone );
536 $new->set_time_zone( 'floating' );
543 my $LastDayOfMonthValidate = { %$NewValidate };
544 foreach ( keys %$LastDayOfMonthValidate )
546 my %copy = %{ $LastDayOfMonthValidate->{$_} };
548 delete $copy{default};
549 $copy{optional} = 1 unless $_ eq 'year' || $_ eq 'month';
551 $LastDayOfMonthValidate->{$_} = \%copy;
554 sub last_day_of_month
557 my %p = validate( @_, $LastDayOfMonthValidate );
559 my $day = $class->_month_length( $p{year}, $p{month} );
561 return $class->new( %p, day => $day );
566 return ( $_[0]->_is_leap_year( $_[1] ) ?
567 $LeapYearMonthLengths[ $_[2] - 1 ] :
568 $MonthLengths[ $_[2] - 1 ]
572 my $FromDayOfYearValidate = { %$NewValidate };
573 foreach ( keys %$FromDayOfYearValidate )
575 next if $_ eq 'month' || $_ eq 'day';
577 my %copy = %{ $FromDayOfYearValidate->{$_} };
579 delete $copy{default};
580 $copy{optional} = 1 unless $_ eq 'year' || $_ eq 'month';
582 $FromDayOfYearValidate->{$_} = \%copy;
584 $FromDayOfYearValidate->{day_of_year} =
587 { 'is between 1 and 366' =>
588 sub { $_[0] >= 1 && $_[0] <= 366 }
594 my %p = validate( @_, $FromDayOfYearValidate );
596 my $is_leap_year = $class->_is_leap_year( $p{year} );
598 Carp::croak( "$p{year} is not a leap year.\n" )
599 if $p{day_of_year} == 366 && ! $is_leap_year;
602 my $day = delete $p{day_of_year};
604 while ( $month <= 12 && $day > $class->_month_length( $p{year}, $month ) )
606 $day -= $class->_month_length( $p{year}, $month );
610 return DateTime->new( %p,
616 sub formatter { $_[0]->{formatter} }
618 sub clone { bless { %{ $_[0] } }, ref $_[0] }
621 Carp::carp('year() is a read-only accessor') if @_ > 1;
622 return $_[0]->{local_c}{year};
625 sub ce_year { $_[0]->{local_c}{year} <= 0 ?
626 $_[0]->{local_c}{year} - 1 :
627 $_[0]->{local_c}{year} }
629 sub era_name { $_[0]->{locale}->era_wide->[ $_[0]->_era_index() ] }
631 sub era_abbr { $_[0]->{locale}->era_abbreviated->[ $_[0]->_era_index() ] }
635 sub _era_index { $_[0]->{local_c}{year} <= 0 ? 0 : 1 }
637 sub christian_era { $_[0]->ce_year > 0 ? 'AD' : 'BC' }
638 sub secular_era { $_[0]->ce_year > 0 ? 'CE' : 'BCE' }
640 sub year_with_era { (abs $_[0]->ce_year) . $_[0]->era_abbr }
641 sub year_with_christian_era { (abs $_[0]->ce_year) . $_[0]->christian_era }
642 sub year_with_secular_era { (abs $_[0]->ce_year) . $_[0]->secular_era }
645 Carp::carp('month() is a read-only accessor') if @_ > 1;
646 return $_[0]->{local_c}{month};
650 sub month_0 { $_[0]->{local_c}{month} - 1 }
653 sub month_name { $_[0]->{locale}->month_format_wide->[ $_[0]->month_0() ] }
655 sub month_abbr { $_[0]->{locale}->month_format_abbreviated->[ $_[0]->month_0() ] }
658 Carp::carp('day_of_month() is a read-only accessor') if @_ > 1;
659 $_[0]->{local_c}{day};
661 *day = \&day_of_month;
662 *mday = \&day_of_month;
664 sub weekday_of_month { use integer; ( ( $_[0]->day - 1 ) / 7 ) + 1 }
666 sub quarter { $_[0]->{local_c}{quarter} }
668 sub quarter_name { $_[0]->{locale}->quarter_format_wide->[ $_[0]->quarter_0() ] }
669 sub quarter_abbr { $_[0]->{locale}->quarter_format_abbreviated->[ $_[0]->quarter_0() ] }
671 sub quarter_0 { $_[0]->{local_c}{quarter} - 1 }
673 sub day_of_month_0 { $_[0]->{local_c}{day} - 1 }
674 *day_0 = \&day_of_month_0;
675 *mday_0 = \&day_of_month_0;
677 sub day_of_week { $_[0]->{local_c}{day_of_week} }
678 *wday = \&day_of_week;
679 *dow = \&day_of_week;
681 sub day_of_week_0 { $_[0]->{local_c}{day_of_week} - 1 }
682 *wday_0 = \&day_of_week_0;
683 *dow_0 = \&day_of_week_0;
685 sub local_day_of_week
689 my $day = $self->day_of_week();
691 my $local_first_day = $self->{locale}->first_day_of_week();
693 my $d = ( ( 8 - $local_first_day ) + $day ) % 7;
695 return $d == 0 ? 7 : $d;
698 sub day_name { $_[0]->{locale}->day_format_wide->[ $_[0]->day_of_week_0() ] }
700 sub day_abbr { $_[0]->{locale}->day_format_abbreviated->[ $_[0]->day_of_week_0() ] }
702 sub day_of_quarter { $_[0]->{local_c}{day_of_quarter} }
703 *doq = \&day_of_quarter;
705 sub day_of_quarter_0 { $_[0]->day_of_quarter - 1 }
706 *doq_0 = \&day_of_quarter_0;
708 sub day_of_year { $_[0]->{local_c}{day_of_year} }
709 *doy = \&day_of_year;
711 sub day_of_year_0 { $_[0]->{local_c}{day_of_year} - 1 }
712 *doy_0 = \&day_of_year_0;
714 sub am_or_pm { $_[0]->{locale}->am_pm_abbreviated->[ $_[0]->hour() < 12 ? 0 : 1 ] }
718 my ( $self, $sep ) = @_;
719 $sep = '-' unless defined $sep;
721 return sprintf( "%0.4d%s%0.2d%s%0.2d",
723 $self->{local_c}{month}, $sep,
724 $self->{local_c}{day} );
730 my ( $self, $sep ) = @_;
731 $sep = '-' unless defined $sep;
733 return sprintf( "%0.2d%s%0.2d%s%0.4d",
734 $self->{local_c}{month}, $sep,
735 $self->{local_c}{day}, $sep,
741 my ( $self, $sep ) = @_;
742 $sep = '-' unless defined $sep;
744 return sprintf( "%0.2d%s%0.2d%s%0.4d",
745 $self->{local_c}{day}, $sep,
746 $self->{local_c}{month}, $sep,
751 Carp::carp('hour() is a read-only accessor') if @_ > 1;
752 return $_[0]->{local_c}{hour};
754 sub hour_1 { $_[0]->{local_c}{hour} == 0 ? 24 : $_[0]->{local_c}{hour} }
756 sub hour_12 { my $h = $_[0]->hour % 12; return $h ? $h : 12 }
757 sub hour_12_0 { $_[0]->hour % 12 }
760 Carp::carp('minute() is a read-only accessor') if @_ > 1;
761 return $_[0]->{local_c}{minute};
766 Carp::carp('second() is a read-only accessor') if @_ > 1;
767 return $_[0]->{local_c}{second};
771 sub fractional_second { $_[0]->second + $_[0]->nanosecond / MAX_NANOSECONDS }
774 Carp::carp('nanosecond() is a read-only accessor') if @_ > 1;
775 return $_[0]->{rd_nanosecs};
778 sub millisecond { _round( $_[0]->{rd_nanosecs} / 1000000 ) }
780 sub microsecond { _round( $_[0]->{rd_nanosecs} / 1000 ) }
787 return $val - $int >= 0.5 ? $int + 1 : $int;
794 return 0 if $self->{tz}->is_floating;
796 return DateTime->_accumulated_leap_seconds( $self->{utc_rd_days} );
803 return $self->iso8601 unless $self->{formatter};
804 return $self->{formatter}->format_datetime($self);
809 my ( $self, $sep ) = @_;
810 $sep = ':' unless defined $sep;
812 return sprintf( "%0.2d%s%0.2d%s%0.2d",
813 $self->{local_c}{hour}, $sep,
814 $self->{local_c}{minute}, $sep,
815 $self->{local_c}{second} );
817 # don't want to override CORE::time()
818 *DateTime::time = \&hms;
820 sub iso8601 { join 'T', $_[0]->ymd('-'), $_[0]->hms(':') }
821 *datetime = \&iso8601;
823 sub is_leap_year { $_[0]->_is_leap_year( $_[0]->year ) }
829 unless ( defined $self->{local_c}{week_year} )
831 # This algorithm was taken from Date::Calc's DateCalc.c file
833 ( ( $self->_ymd2rd( $self->year, 1, 1 ) + 6 ) % 7 );
835 $self->{local_c}{week_number} =
836 int( ( ( $self->day_of_year - 1 ) + $jan_one_dow_m1 ) / 7 );
837 $self->{local_c}{week_number}++ if $jan_one_dow_m1 < 4;
839 if ( $self->{local_c}{week_number} == 0 )
841 $self->{local_c}{week_year} = $self->year - 1;
842 $self->{local_c}{week_number} =
843 $self->_weeks_in_year( $self->{local_c}{week_year} );
845 elsif ( $self->{local_c}{week_number} == 53 &&
846 $self->_weeks_in_year( $self->year ) == 52 )
848 $self->{local_c}{week_number} = 1;
849 $self->{local_c}{week_year} = $self->year + 1;
853 $self->{local_c}{week_year} = $self->year;
857 return @{ $self->{local_c} }{ 'week_year', 'week_number' }
860 # Also from DateCalc.c
867 ( ( $self->_ymd2rd( $year, 1, 1 ) + 6 ) % 7 ) + 1;
869 ( ( $self->_ymd2rd( $year, 12, 31 ) + 6 ) % 7 ) + 1;
871 return $jan_one_dow == 4 || $dec_31_dow == 4 ? 53 : 52;
874 sub week_year { ($_[0]->week)[0] }
875 sub week_number { ($_[0]->week)[1] }
877 # ISO says that the first week of a year is the first week containing
878 # a Thursday. Extending that says that the first week of the month is
879 # the first week containing a Thursday. ICU agrees.
881 # Algorithm supplied by Rick Measham, who doesn't understand how it
882 # works. Neither do I. Please feel free to explain this to me!
887 # Faster than cloning just to get the dow
888 my $first_wday_of_month = ( 8 - ( $self->day - $self->dow ) % 7 ) % 7;
889 $first_wday_of_month = 7 unless $first_wday_of_month;
891 my $wom = int( ( $self->day + $first_wday_of_month - 2 ) / 7 );
892 return ( $first_wday_of_month <= 4 ) ? $wom + 1 : $wom;
896 Carp::carp('time_zone() is a read-only accessor') if @_ > 1;
900 sub offset { $_[0]->{tz}->offset_for_datetime( $_[0] ) }
901 sub _offset_for_local_datetime { $_[0]->{tz}->offset_for_local_datetime( $_[0] ) }
903 sub is_dst { $_[0]->{tz}->is_dst_for_datetime( $_[0] ) }
905 sub time_zone_long_name { $_[0]->{tz}->name }
906 sub time_zone_short_name { $_[0]->{tz}->short_name_for_datetime( $_[0] ) }
909 Carp::carp('locale() is a read-only accessor') if @_ > 1;
910 return $_[0]->{locale};
912 *language = \&locale;
914 sub utc_rd_values { @{ $_[0] }{ 'utc_rd_days', 'utc_rd_secs', 'rd_nanosecs' } }
915 sub local_rd_values { @{ $_[0] }{ 'local_rd_days', 'local_rd_secs', 'rd_nanosecs' } }
917 # NOTE: no nanoseconds, no leap seconds
918 sub utc_rd_as_seconds { ( $_[0]->{utc_rd_days} * SECONDS_PER_DAY ) + $_[0]->{utc_rd_secs} }
920 # NOTE: no nanoseconds, no leap seconds
921 sub local_rd_as_seconds { ( $_[0]->{local_rd_days} * SECONDS_PER_DAY ) + $_[0]->{local_rd_secs} }
923 # RD 1 is JD 1,721,424.5 - a simple offset
928 my $jd = $self->{utc_rd_days} + 1_721_424.5;
930 my $day_length = $self->_day_length( $self->{utc_rd_days} );
933 ( $self->{utc_rd_secs} / $day_length ) +
934 ( $self->{rd_nanosecs} / $day_length / MAX_NANOSECONDS )
938 sub mjd { $_[0]->jd - 2_400_000.5 }
941 my %strftime_patterns =
942 ( 'a' => sub { $_[0]->day_abbr },
943 'A' => sub { $_[0]->day_name },
944 'b' => sub { $_[0]->month_abbr },
945 'B' => sub { $_[0]->month_name },
946 'c' => sub { $_[0]->format_cldr( $_[0]->{locale}->datetime_format_default() ) },
947 'C' => sub { int( $_[0]->year / 100 ) },
948 'd' => sub { sprintf( '%02d', $_[0]->day_of_month ) },
949 'D' => sub { $_[0]->strftime( '%m/%d/%y' ) },
950 'e' => sub { sprintf( '%2d', $_[0]->day_of_month ) },
951 'F' => sub { $_[0]->ymd('-') },
952 'g' => sub { substr( $_[0]->week_year, -2 ) },
953 'G' => sub { $_[0]->week_year },
954 'H' => sub { sprintf( '%02d', $_[0]->hour ) },
955 'I' => sub { sprintf( '%02d', $_[0]->hour_12 ) },
956 'j' => sub { $_[0]->day_of_year },
957 'k' => sub { sprintf( '%2d', $_[0]->hour ) },
958 'l' => sub { sprintf( '%2d', $_[0]->hour_12 ) },
959 'm' => sub { sprintf( '%02d', $_[0]->month ) },
960 'M' => sub { sprintf( '%02d', $_[0]->minute ) },
961 'n' => sub { "\n" }, # should this be OS-sensitive?
962 'N' => \&_format_nanosecs,
963 'p' => sub { $_[0]->am_or_pm() },
964 'P' => sub { lc $_[0]->am_or_pm() },
965 'r' => sub { $_[0]->strftime( '%I:%M:%S %p' ) },
966 'R' => sub { $_[0]->strftime( '%H:%M' ) },
967 's' => sub { $_[0]->epoch },
968 'S' => sub { sprintf( '%02d', $_[0]->second ) },
970 'T' => sub { $_[0]->strftime( '%H:%M:%S' ) },
971 'u' => sub { $_[0]->day_of_week },
972 # algorithm from Date::Format::wkyr
973 'U' => sub { my $dow = $_[0]->day_of_week;
974 $dow = 0 if $dow == 7; # convert to 0-6, Sun-Sat
975 my $doy = $_[0]->day_of_year - 1;
976 return sprintf( '%02d', int( ( $doy - $dow + 13 ) / 7 - 1 ) )
978 'V' => sub { sprintf( '%02d', $_[0]->week_number ) },
979 'w' => sub { my $dow = $_[0]->day_of_week;
982 'W' => sub { my $dow = $_[0]->day_of_week;
983 my $doy = $_[0]->day_of_year - 1;
984 return sprintf( '%02d', int( ( $doy - $dow + 13 ) / 7 - 1 ) )
986 'x' => sub { $_[0]->format_cldr( $_[0]->{locale}->date_format_default() ) },
987 'X' => sub { $_[0]->format_cldr( $_[0]->{locale}->time_format_default() ) },
988 'y' => sub { sprintf( '%02d', substr( $_[0]->year, -2 ) ) },
989 'Y' => sub { return $_[0]->year },
990 'z' => sub { DateTime::TimeZone->offset_as_string( $_[0]->offset ) },
991 'Z' => sub { $_[0]->{tz}->short_name_for_datetime( $_[0] ) },
995 $strftime_patterns{h} = $strftime_patterns{b};
1000 # make a copy or caller's scalars get munged
1004 foreach my $p (@patterns)
1008 %{(\w+)} # method name like %{day_name}
1010 %([%a-zA-Z]) # single character specifier like %d
1012 %(\d+)N # special case for %N
1016 ? ( $self->can($1) ? $self->$1() : "\%{$1}" )
1018 ? ( $strftime_patterns{$2} ? $strftime_patterns{$2}->($self) : "\%$2" )
1020 ? $strftime_patterns{N}->($self, $3)
1021 : '' # this won't happen
1025 return $p unless wantarray;
1035 # It's an array because the order in which the regexes are checked
1036 # is important. These patterns are similar to the ones Java uses,
1037 # but not quite the same. See
1038 # http://www.unicode.org/reports/tr35/tr35-9.html#Date_Format_Patterns.
1040 ( qr/GGGGG/ => sub { $_[0]->{locale}->era_narrow->[ $_[0]->_era_index() ] },
1041 qr/GGGG/ => 'era_name',
1042 qr/G{1,3}/ => 'era_abbr',
1044 qr/(y{3,5})/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->year() ) },
1045 # yy is a weird special case, where it must be exactly 2 digits
1046 qr/yy/ => sub { my $year = $_[0]->year();
1047 my $y2 = substr( $year, -2, 2 ) if length $year > 2;
1048 $y2 *= -1 if $year < 0;
1049 $_[0]->_zero_padded_number( 'yy', $y2 ) },
1050 qr/y/ => sub { $_[0]->year() },
1051 qr/(u+)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->year() ) },
1052 qr/(Y+)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->week_year() ) },
1054 qr/QQQQ/ => 'quarter_name',
1055 qr/QQQ/ => 'quarter_abbr',
1056 qr/(QQ?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->quarter() ) },
1058 qr/qqqq/ => sub { $_[0]->{locale}->quarter_stand_alone_wide()->[ $_[0]->quarter_0() ] },
1059 qr/qqq/ => sub { $_[0]->{locale}->quarter_stand_alone_abbreviated()->[ $_[0]->quarter_0() ] },
1060 qr/(qq?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->quarter() ) },
1062 qr/MMMMM/ => sub { $_[0]->{locale}->month_format_narrow->[ $_[0]->month_0() ] },
1063 qr/MMMM/ => 'month_name',
1064 qr/MMM/ => 'month_abbr',
1065 qr/(MM?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->month() ) },
1067 qr/LLLLL/ => sub { $_[0]->{locale}->month_stand_alone_narrow->[ $_[0]->month_0() ] },
1068 qr/LLLL/ => sub { $_[0]->{locale}->month_stand_alone_wide->[ $_[0]->month_0() ] },
1069 qr/LLL/ => sub { $_[0]->{locale}->month_stand_alone_abbreviated->[ $_[0]->month_0() ] },
1070 qr/(LL?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->month() ) },
1072 qr/(ww?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->week_number() ) },
1073 qr/W/ => 'week_of_month',
1075 qr/(dd?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->day_of_month() ) },
1076 qr/(D{1,3})/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->day_of_year() ) },
1078 qr/F/ => 'weekday_of_month',
1079 qr/(g+)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->mjd() ) },
1081 qr/EEEEE/ => sub { $_[0]->{locale}->day_format_narrow->[ $_[0]->day_of_week_0() ] },
1082 qr/EEEE/ => 'day_name',
1083 qr/E{1,3}/ => 'day_abbr',
1085 qr/eeeee/ => sub { $_[0]->{locale}->day_format_narrow->[ $_[0]->day_of_week_0() ] },
1086 qr/eeee/ => 'day_name',
1087 qr/eee/ => 'day_abbr',
1088 qr/(ee?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->local_day_of_week() ) },
1090 qr/ccccc/ => sub { $_[0]->{locale}->day_stand_alone_narrow->[ $_[0]->day_of_week_0() ] },
1091 qr/cccc/ => sub { $_[0]->{locale}->day_stand_alone_wide->[ $_[0]->day_of_week_0() ] },
1092 qr/ccc/ => sub { $_[0]->{locale}->day_stand_alone_abbreviated->[ $_[0]->day_of_week_0() ] },
1093 qr/(cc?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->day_of_week() ) },
1095 qr/a/ => 'am_or_pm',
1097 qr/(hh?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->hour_12() ) },
1098 qr/(HH?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->hour() ) },
1099 qr/(KK?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->hour_12_0() ) },
1100 qr/(kk?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->hour_1() ) },
1101 qr/(jj?)/ => sub { my $h = $_[0]->{locale}->prefers_24_hour_time() ? $_[0]->hour() : $_[0]->hour_12();
1102 $_[0]->_zero_padded_number( $1, $h ) },
1104 qr/(mm?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->minute() ) },
1106 qr/(ss?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->second() ) },
1107 # I'm not sure this is what is wanted (notably the trailing
1108 # and leading zeros it can produce), but once again the LDML
1109 # spec is not all that clear.
1110 qr/(S+)/ => sub { my $l = length $1;
1111 my $val = sprintf( "%.${l}f", $_[0]->fractional_second() - $_[0]->second() );
1114 qr/A+/ => sub { ( $_[0]->{local_rd_secs} * 1000 ) + $_[0]->millisecond() },
1116 qr/zzzz/ => sub { $_[0]->time_zone_long_name() },
1117 qr/z{1,3}/ => sub { $_[0]->time_zone_short_name() },
1118 qr/ZZZZ/ => sub { $_[0]->time_zone_short_name()
1119 . DateTime::TimeZone->offset_as_string( $_[0]->offset() ) },
1120 qr/Z{1,3}/ => sub { DateTime::TimeZone->offset_as_string( $_[0]->offset() ) },
1121 qr/vvvv/ => sub { $_[0]->time_zone_long_name() },
1122 qr/v{1,3}/ => sub { $_[0]->time_zone_short_name() },
1123 qr/VVVV/ => sub { $_[0]->time_zone_long_name() },
1124 qr/V{1,3}/ => sub { $_[0]->time_zone_short_name() },
1127 sub _zero_padded_number
1130 my $size = length shift;
1133 return sprintf( "%0${size}d", $val );
1136 sub _space_padded_string
1139 my $size = length shift;
1142 return sprintf( "% ${size}s", $val );
1148 # make a copy or caller's scalars get munged
1152 foreach my $p (@patterns)
1156 '((?:[^']|'')*)' # quote escaped bit of text
1157 # it needs to end with one
1158 # quote not followed by
1161 (([a-zA-Z])\3*) # could be a pattern
1169 ? $self->_cldr_pattern($2)
1172 : undef # should never get here
1177 return $p unless wantarray;
1188 my $pattern = shift;
1190 for ( my $i = 0; $i < @patterns; $i +=2 )
1192 if ( $pattern =~ /$patterns[$i]/ )
1194 my $sub = $patterns[ $i + 1 ];
1196 return $self->$sub();
1204 sub _format_nanosecs
1207 my $precision = shift;
1209 my $ret = sprintf( "%09d", $self->{rd_nanosecs} );
1210 return $ret unless $precision; # default = 9 digits
1212 # rd_nanosecs might contain a fractional separator
1213 my ( $int, $frac ) = split /[.,]/, $self->{rd_nanosecs};
1214 $ret .= $frac if $frac;
1216 return substr( $ret, 0, $precision );
1223 return $self->{utc_c}{epoch}
1224 if exists $self->{utc_c}{epoch};
1226 my ( $year, $month, $day ) = $self->_utc_ymd;
1227 my @hms = $self->_utc_hms;
1229 $self->{utc_c}{epoch} =
1230 timegm_nocheck( ( reverse @hms ),
1236 return $self->{utc_c}{epoch};
1243 my $epoch = $self->epoch;
1245 return undef unless defined $epoch;
1247 my $nano = $self->{rd_nanosecs} / MAX_NANOSECONDS;
1249 return $epoch + $nano;
1253 sub is_infinite { 0 }
1255 # added for benefit of DateTime::TimeZone
1256 sub utc_year { $_[0]->{utc_year} }
1258 # returns a result that is relative to the first datetime
1259 sub subtract_datetime
1264 $dt2 = $dt2->clone->set_time_zone( $dt1->time_zone )
1265 unless $dt1->time_zone eq $dt2->time_zone;
1267 # We only want a negative duration if $dt2 > $dt1 ($self)
1268 my ( $bigger, $smaller, $negative ) =
1274 my $is_floating = $dt1->time_zone->is_floating &&
1275 $dt2->time_zone->is_floating;
1278 my $minute_length = 60;
1279 unless ($is_floating)
1281 my ( $utc_rd_days, $utc_rd_secs ) = $smaller->utc_rd_values;
1283 if ( $utc_rd_secs >= 86340 && ! $is_floating )
1285 # If the smaller of the two datetimes occurs in the last
1286 # UTC minute of the UTC day, then that minute may not be
1287 # 60 seconds long. If we need to subtract a minute from
1288 # the larger datetime's minutes count in order to adjust
1289 # the seconds difference to be positive, we need to know
1290 # how long that minute was. If one of the datetimes is
1291 # floating, we just assume a minute is 60 seconds.
1293 $minute_length = $dt1->_day_length($utc_rd_days) - 86340;
1297 # This is a gross hack that basically figures out if the bigger of
1298 # the two datetimes is the day of a DST change. If it's a 23 hour
1299 # day (switching _to_ DST) then we subtract 60 minutes from the
1300 # local time. If it's a 25 hour day then we add 60 minutes to the
1303 # This produces the most "intuitive" results, though there are
1304 # still reversibility problems with the resultant duration.
1306 # However, if the two objects are on the same (local) date, and we
1307 # are not crossing a DST change, we don't want to invoke the hack
1308 # - see 38local-subtract.t
1309 my $bigger_min = $bigger->hour * 60 + $bigger->minute;
1310 if ( $bigger->time_zone->has_dst_changes
1311 && $bigger->is_dst != $smaller->is_dst
1316 # it's a 23 hour (local) day
1317 if ( $bigger->is_dst
1320 my $prev_day = eval { $bigger->clone->subtract( days => 1 ) };
1321 $prev_day && ! $prev_day->is_dst ? 1 : 0 }
1325 # it's a 25 hour (local) day
1326 if ( ! $bigger->is_dst
1329 my $prev_day = eval { $bigger->clone->subtract( days => 1 ) };
1330 $prev_day && $prev_day->is_dst ? 1 : 0 }
1334 my ( $months, $days, $minutes, $seconds, $nanoseconds ) =
1335 $dt1->_adjust_for_positive_difference
1336 ( $bigger->year * 12 + $bigger->month, $smaller->year * 12 + $smaller->month,
1338 $bigger->day, $smaller->day,
1340 $bigger_min, $smaller->hour * 60 + $smaller->minute,
1342 $bigger->second, $smaller->second,
1344 $bigger->nanosecond, $smaller->nanosecond,
1348 # XXX - using the smaller as the month length is
1349 # somewhat arbitrary, we could also use the bigger -
1350 # either way we have reversibility problems
1351 $dt1->_month_length( $smaller->year, $smaller->month ),
1356 for ( $months, $days, $minutes, $seconds, $nanoseconds )
1358 # Some versions of Perl can end up with -0 if we do "0 * -1"!!
1364 $dt1->duration_class->new
1365 ( months => $months,
1367 minutes => $minutes,
1368 seconds => $seconds,
1369 nanoseconds => $nanoseconds,
1373 sub _adjust_for_positive_difference
1385 if ( $nano1 < $nano2 )
1388 $nano1 += MAX_NANOSECONDS;
1391 if ( $sec1 < $sec2 )
1394 $sec1 += $minute_length;
1397 # A day always has 24 * 60 minutes, though the minutes may vary in
1399 if ( $min1 < $min2 )
1405 if ( $day1 < $day2 )
1408 $day1 += $month_length;
1411 return ( $month1 - $month2,
1419 sub subtract_datetime_absolute
1424 my $utc_rd_secs1 = $self->utc_rd_as_seconds;
1425 $utc_rd_secs1 += DateTime->_accumulated_leap_seconds( $self->{utc_rd_days} )
1426 if ! $self->time_zone->is_floating;
1428 my $utc_rd_secs2 = $dt->utc_rd_as_seconds;
1429 $utc_rd_secs2 += DateTime->_accumulated_leap_seconds( $dt->{utc_rd_days} )
1430 if ! $dt->time_zone->is_floating;
1432 my $seconds = $utc_rd_secs1 - $utc_rd_secs2;
1433 my $nanoseconds = $self->nanosecond - $dt->nanosecond;
1435 if ( $nanoseconds < 0 )
1438 $nanoseconds += MAX_NANOSECONDS;
1442 $self->duration_class->new
1443 ( seconds => $seconds,
1444 nanoseconds => $nanoseconds,
1453 my ( $smaller, $bigger ) = sort $self, $dt;
1455 my ( $months, $days, undef, undef, undef ) =
1456 $dt->_adjust_for_positive_difference
1457 ( $bigger->year * 12 + $bigger->month, $smaller->year * 12 + $smaller->month,
1459 $bigger->day, $smaller->day,
1469 $smaller->_month_length( $smaller->year, $smaller->month ),
1472 return $self->duration_class->new( months => $months,
1481 my $days = abs( ($self->local_rd_values)[0] - ($dt->local_rd_values)[0] );
1483 $self->duration_class->new( days => $days );
1491 my ( $smaller, $greater ) = sort $self, $dt;
1493 my $days = int( $greater->jd - $smaller->jd );
1495 my $dur = $greater->subtract_datetime($smaller);
1498 $p{hours} = $dur->hours + ( $days * 24 );
1499 $p{minutes} = $dur->minutes;
1500 $p{seconds} = $dur->seconds;
1502 return $self->duration_class->new(%p);
1507 my ( $dt, $dur, $reversed ) = @_;
1511 ( $dur, $dt ) = ( $dt, $dur );
1514 unless ( DateTime::Helpers::isa( $dur, 'DateTime::Duration' ) )
1516 my $class = ref $dt;
1517 my $dt_string = overload::StrVal($dt);
1519 Carp::croak( "Cannot add $dur to a $class object ($dt_string).\n"
1520 . " Only a DateTime::Duration object can "
1521 . " be added to a $class object." );
1524 return $dt->clone->add_duration($dur);
1527 sub _subtract_overload
1529 my ( $date1, $date2, $reversed ) = @_;
1533 ( $date2, $date1 ) = ( $date1, $date2 );
1536 if ( DateTime::Helpers::isa( $date2, 'DateTime::Duration' ) )
1538 my $new = $date1->clone;
1539 $new->add_duration( $date2->inverse );
1542 elsif ( DateTime::Helpers::isa( $date2, 'DateTime' ) )
1544 return $date1->subtract_datetime($date2);
1548 my $class = ref $date1;
1549 my $dt_string = overload::StrVal($date1);
1551 Carp::croak( "Cannot subtract $date2 from a $class object ($dt_string).\n"
1552 . " Only a DateTime::Duration or DateTime object can "
1553 . " be subtracted from a $class object." );
1561 return $self->add_duration( $self->duration_class->new(@_) );
1568 return $self->subtract_duration( $self->duration_class->new(@_) );
1571 sub subtract_duration { return $_[0]->add_duration( $_[1]->inverse ) }
1574 my @spec = ( { isa => 'DateTime::Duration' } );
1578 my ($dur) = validate_pos( @_, @spec );
1580 # simple optimization
1581 return $self if $dur->is_zero;
1583 my %deltas = $dur->deltas;
1585 # This bit isn't quite right since DateTime::Infinite::Future -
1586 # infinite duration should NaN
1587 foreach my $val ( values %deltas )
1590 if ( $val == INFINITY )
1592 $inf = DateTime::Infinite::Future->new;
1594 elsif ( $val == NEG_INFINITY )
1596 $inf = DateTime::Infinite::Past->new;
1602 bless $self, ref $inf;
1608 return $self if $self->is_infinite;
1610 if ( $deltas{days} )
1612 $self->{local_rd_days} += $deltas{days};
1614 $self->{utc_year} += int( $deltas{days} / 365 ) + 1;
1617 if ( $deltas{months} )
1619 # For preserve mode, if it is the last day of the month, make
1620 # it the 0th day of the following month (which then will
1621 # normalize back to the last day of the new month).
1622 my ($y, $m, $d) = ( $dur->is_preserve_mode ?
1623 $self->_rd2ymd( $self->{local_rd_days} + 1 ) :
1624 $self->_rd2ymd( $self->{local_rd_days} )
1627 $d -= 1 if $dur->is_preserve_mode;
1629 if ( ! $dur->is_wrap_mode && $d > 28 )
1631 # find the rd for the last day of our target month
1632 $self->{local_rd_days} = $self->_ymd2rd( $y, $m + $deltas{months} + 1, 0 );
1634 # what day of the month is it? (discard year and month)
1635 my $last_day = ($self->_rd2ymd( $self->{local_rd_days} ))[2];
1637 # if our original day was less than the last day,
1639 $self->{local_rd_days} -= $last_day - $d if $last_day > $d;
1643 $self->{local_rd_days} = $self->_ymd2rd( $y, $m + $deltas{months}, $d );
1646 $self->{utc_year} += int( $deltas{months} / 12 ) + 1;
1649 if ( $deltas{days} || $deltas{months} )
1651 $self->_calc_utc_rd;
1653 $self->_handle_offset_modifier( $self->second );
1656 if ( $deltas{minutes} )
1658 $self->{utc_rd_secs} += $deltas{minutes} * 60;
1660 # This intentionally ignores leap seconds
1661 $self->_normalize_tai_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} );
1664 if ( $deltas{seconds} || $deltas{nanoseconds} )
1666 $self->{utc_rd_secs} += $deltas{seconds};
1668 if ( $deltas{nanoseconds} )
1670 $self->{rd_nanosecs} += $deltas{nanoseconds};
1671 $self->_normalize_nanoseconds( $self->{utc_rd_secs}, $self->{rd_nanosecs} );
1674 $self->_normalize_seconds;
1676 # This might be some big number much bigger than 60, but
1677 # that's ok (there are tests in 19leap_second.t to confirm
1679 $self->_handle_offset_modifier( $self->second + $deltas{seconds} );
1683 (ref $self)->from_object
1685 locale => $self->{locale},
1686 ( $self->{formatter} ? ( formatter => $self->{formatter} ) : () ),
1695 sub _compare_overload
1697 # note: $_[1]->compare( $_[0] ) is an error when $_[1] is not a
1698 # DateTime (such as the INFINITY value)
1699 return $_[2] ? - $_[0]->compare( $_[1] ) : $_[0]->compare( $_[1] );
1704 shift->_compare( @_, 0 );
1707 sub compare_ignore_floating
1709 shift->_compare( @_, 1 );
1714 my ( $class, $dt1, $dt2, $consistent ) = ref $_[0] ? ( undef, @_ ) : @_;
1716 return undef unless defined $dt2;
1718 if ( ! ref $dt2 && ( $dt2 == INFINITY || $dt2 == NEG_INFINITY ) )
1720 return $dt1->{utc_rd_days} <=> $dt2;
1723 unless ( DateTime::Helpers::can( $dt1, 'utc_rd_values' )
1724 && DateTime::Helpers::can( $dt2, 'utc_rd_values' ) )
1726 my $dt1_string = overload::StrVal($dt1);
1727 my $dt2_string = overload::StrVal($dt2);
1729 Carp::croak( "A DateTime object can only be compared to"
1730 . " another DateTime object ($dt1_string, $dt2_string)." );
1733 if ( ! $consistent &&
1734 DateTime::Helpers::can( $dt1, 'time_zone' ) &&
1735 DateTime::Helpers::can( $dt2, 'time_zone' )
1738 my $is_floating1 = $dt1->time_zone->is_floating;
1739 my $is_floating2 = $dt2->time_zone->is_floating;
1741 if ( $is_floating1 && ! $is_floating2 )
1743 $dt1 = $dt1->clone->set_time_zone( $dt2->time_zone );
1745 elsif ( $is_floating2 && ! $is_floating1 )
1747 $dt2 = $dt2->clone->set_time_zone( $dt1->time_zone );
1751 my @dt1_components = $dt1->utc_rd_values;
1752 my @dt2_components = $dt2->utc_rd_values;
1754 foreach my $i ( 0..2 )
1756 return $dt1_components[$i] <=> $dt2_components[$i]
1757 if $dt1_components[$i] != $dt2_components[$i]
1763 sub _string_equals_overload
1765 my ( $class, $dt1, $dt2 ) = ref $_[0] ? ( undef, @_ ) : @_;
1768 ( DateTime::Helpers::can( $dt1, 'utc_rd_values' )
1769 && DateTime::Helpers::can( $dt2, 'utc_rd_values' )
1772 $class ||= ref $dt1;
1773 return ! $class->compare( $dt1, $dt2 );
1776 sub _string_not_equals_overload
1778 return ! _string_equals_overload(@_);
1781 sub _normalize_nanoseconds
1785 # seconds, nanoseconds
1788 my $overflow = 1 + $_[2] / MAX_NANOSECONDS;
1789 $_[2] += $overflow * MAX_NANOSECONDS;
1792 elsif ( $_[2] >= MAX_NANOSECONDS )
1794 my $overflow = $_[2] / MAX_NANOSECONDS;
1795 $_[2] -= $overflow * MAX_NANOSECONDS;
1800 # Many of the same parameters as new() but all of them are optional,
1801 # and there are no defaults.
1803 { map { my %copy = %{ $BasicValidate->{$_} };
1804 delete $copy{default};
1805 $copy{optional} = 1;
1807 keys %$BasicValidate };
1812 my %p = validate( @_, $SetValidate );
1814 my $new_dt = $self->_new_from_self(%p);
1821 sub set_year { $_[0]->set( year => $_[1] ) }
1822 sub set_month { $_[0]->set( month => $_[1] ) }
1823 sub set_day { $_[0]->set( day => $_[1] ) }
1824 sub set_hour { $_[0]->set( hour => $_[1] ) }
1825 sub set_minute { $_[0]->set( minute => $_[1] ) }
1826 sub set_second { $_[0]->set( second => $_[1] ) }
1827 sub set_nanosecond { $_[0]->set( nanosecond => $_[1] ) }
1829 sub set_locale { $_[0]->set( locale => $_[1] ) }
1831 sub set_formatter { $_[0]->{formatter} = $_[1] }
1834 my %TruncateDefault = ( month => 1,
1841 my $re = join '|', 'year', 'week', grep { $_ ne 'nanosecond' } keys %TruncateDefault;
1842 my $spec = { to => { regex => qr/^(?:$re)/ } };
1847 my %p = validate( @_, $spec );
1850 if ( $p{to} eq 'week' )
1852 my $day_diff = $self->day_of_week - 1;
1856 $self->add( days => -1 * $day_diff );
1859 return $self->truncate( to => 'day' );
1864 foreach my $f ( qw( year month day hour minute second nanosecond ) )
1866 $new{$f} = $truncate ? $TruncateDefault{$f} : $self->$f();
1868 $truncate = 1 if $p{to} eq $f;
1872 my $new_dt = $self->_new_from_self(%new);
1882 my ( $self, $tz ) = @_;
1884 # This is a bit of a hack but it works because time zone objects
1885 # are singletons, and if it doesn't work all we lose is a little
1887 return $self if $self->{tz} eq $tz;
1889 my $was_floating = $self->{tz}->is_floating;
1891 $self->{tz} = ref $tz ? $tz : DateTime::TimeZone->new( name => $tz );
1893 $self->_handle_offset_modifier( $self->second, 1 );
1895 # if it either was or now is floating (but not both)
1896 if ( $self->{tz}->is_floating xor $was_floating )
1898 $self->_calc_utc_rd;
1900 elsif ( ! $was_floating )
1902 $self->_calc_local_rd;
1911 my $cloning = shift;
1913 my $serialized = '';
1914 foreach my $key ( qw( utc_rd_days
1918 $serialized .= "$key:$self->{$key}|";
1921 # not used yet, but may be handy in the future.
1922 $serialized .= "version:$VERSION";
1924 # Formatter needs to be returned as a reference since it may be
1925 # undef or a class name, and Storable will complain if extra
1926 # return values aren't refs
1927 return $serialized, $self->{locale}, $self->{tz}, \$self->{formatter};
1933 my $cloning = shift;
1934 my $serialized = shift;
1936 my %serialized = map { split /:/ } split /\|/, $serialized;
1938 my ( $locale, $tz, $formatter );
1940 # more recent code version
1943 ( $locale, $tz, $formatter ) = @_;
1947 $tz = DateTime::TimeZone->new( name => delete $serialized{tz} );
1950 DateTime::Locale->load( exists $serialized{language}
1951 ? delete $serialized{language}
1952 : delete $serialized{locale}
1956 delete $serialized{version};
1958 my $object = bless { utc_vals => [ $serialized{utc_rd_days},
1959 $serialized{utc_rd_secs},
1960 $serialized{rd_nanosecs},
1963 }, 'DateTime::_Thawed';
1965 my %formatter = defined $$formatter ? ( formatter => $$formatter ) : ();
1966 my $new = (ref $self)->from_object( object => $object,
1977 package DateTime::_Thawed;
1979 sub utc_rd_values { @{ $_[0]->{utc_vals} } }
1981 sub time_zone { $_[0]->{tz} }
1990 DateTime - A date and time object
1996 $dt = DateTime->new( year => 1964,
2002 nanosecond => 500000000,
2003 time_zone => 'Asia/Taipei',
2006 $dt = DateTime->from_epoch( epoch => $epoch );
2007 $dt = DateTime->now; # same as ( epoch => time() )
2010 $month = $dt->month; # 1-12 - also mon
2012 $day = $dt->day; # 1-31 - also day_of_month, mday
2014 $dow = $dt->day_of_week; # 1-7 (Monday is 1) - also dow, wday
2016 $hour = $dt->hour; # 0-23
2017 $minute = $dt->minute; # 0-59 - also min
2019 $second = $dt->second; # 0-61 (leap seconds!) - also sec
2021 $doy = $dt->day_of_year; # 1-366 (leap years) - also doy
2023 $doq = $dt->day_of_quarter; # 1.. - also doq
2025 $qtr = $dt->quarter; # 1-4
2027 # all of the start-at-1 methods above have correponding start-at-0
2028 # methods, such as $dt->day_of_month_0, $dt->month_0 and so on
2030 $ymd = $dt->ymd; # 2002-12-06
2031 $ymd = $dt->ymd('/'); # 2002/12/06 - also date
2033 $mdy = $dt->mdy; # 12-06-2002
2034 $mdy = $dt->mdy('/'); # 12/06/2002
2036 $dmy = $dt->dmy; # 06-12-2002
2037 $dmy = $dt->dmy('/'); # 06/12/2002
2039 $hms = $dt->hms; # 14:02:29
2040 $hms = $dt->hms('!'); # 14!02!29 - also time
2042 $is_leap = $dt->is_leap_year;
2044 # these are localizable, see Locales section
2045 $month_name = $dt->month_name; # January, February, ...
2046 $month_abbr = $dt->month_abbr; # Jan, Feb, ...
2047 $day_name = $dt->day_name; # Monday, Tuesday, ...
2048 $day_abbr = $dt->day_abbr; # Mon, Tue, ...
2050 # May not work for all possible datetime, see the docs on this
2051 # method for more details.
2052 $epoch_time = $dt->epoch;
2054 $dt2 = $dt + $duration_object;
2056 $dt3 = $dt - $duration_object;
2058 $duration_object = $dt - $dt2;
2060 $dt->set( year => 1882 );
2062 $dt->set_time_zone( 'America/Chicago' );
2064 $dt->set_formatter( $formatter );
2068 DateTime is a class for the representation of date/time combinations,
2069 and is part of the Perl DateTime project. For details on this project
2070 please see L<http://datetime.perl.org/>. The DateTime site has a FAQ
2071 which may help answer many "how do I do X?" questions. The FAQ is at
2072 L<http://datetime.perl.org/?FAQ>.
2074 It represents the Gregorian calendar, extended backwards in time
2075 before its creation (in 1582). This is sometimes known as the
2076 "proleptic Gregorian calendar". In this calendar, the first day of
2077 the calendar (the epoch), is the first day of year 1, which
2078 corresponds to the date which was (incorrectly) believed to be the
2079 birth of Jesus Christ.
2081 The calendar represented does have a year 0, and in that way differs
2082 from how dates are often written using "BCE/CE" or "BC/AD".
2084 For infinite datetimes, please see the
2085 L<DateTime::Infinite|DateTime::Infinite> module.
2089 =head2 0-based Versus 1-based Numbers
2091 The DateTime.pm module follows a simple consistent logic for
2092 determining whether or not a given number is 0-based or 1-based.
2094 Month, day of month, day of week, and day of year are 1-based. Any
2095 method that is 1-based also has an equivalent 0-based method ending in
2096 "_0". So for example, this class provides both C<day_of_week()> and
2097 C<day_of_week_0()> methods.
2099 The C<day_of_week_0()> method still treats Monday as the first day of
2102 All I<time>-related numbers such as hour, minute, and second are
2105 Years are neither, as they can be both positive or negative, unlike
2106 any other datetime component. There I<is> a year 0.
2108 There is no C<quarter_0()> method.
2110 =head2 Error Handling
2112 Some errors may cause this module to die with an error string. This
2113 can only happen when calling constructor methods, methods that change
2114 the object, such as C<set()>, or methods that take parameters.
2115 Methods that retrieve information about the object, such as C<year()>
2116 or C<epoch()>, will never die.
2120 All the object methods which return names or abbreviations return data
2121 based on a locale. This is done by setting the locale when
2122 constructing a DateTime object. There is also a C<DefaultLocale()>
2123 class method which may be used to set the default locale for all
2124 DateTime objects created. If this is not set, then "en_US" is used.
2126 =head2 Floating DateTimes
2128 The default time zone for new DateTime objects, except where stated
2129 otherwise, is the "floating" time zone. This concept comes from the
2130 iCal standard. A floating datetime is one which is not anchored to
2131 any particular time zone. In addition, floating datetimes do not
2132 include leap seconds, since we cannot apply them without knowing the
2133 datetime's time zone.
2135 The results of date math and comparison between a floating datetime
2136 and one with a real time zone are not really valid, because one
2137 includes leap seconds and the other does not. Similarly, the results
2138 of datetime math between two floating datetimes and two datetimes with
2139 time zones are not really comparable.
2141 If you are planning to use any objects with a real time zone, it is
2142 strongly recommended that you B<do not> mix these with floating
2147 If you are going to be using doing date math, please read the section
2148 L<How Datetime Math is Done>.
2150 =head2 Time Zone Warnings
2152 Determining the local time zone for a system can be slow. If C<$ENV{TZ}> is
2153 not set, it may involve reading a number of files in F</etc> or elsewhere. If
2154 you know that the local time zone won't change while your code is running, and
2155 you need to make many objects for the local time zone, it is strongly
2156 recommended that you retrieve the local time zone once and cache it:
2158 our $App::LocalTZ = DateTime::TimeZone->new( name => 'local' );
2160 ... # then everywhere else
2162 my $dt = DateTime->new( ..., time_zone => $App::LocalTZ );
2164 DateTime itself does not do this internally because local time zones can
2165 change, and there's no good way to determine if it's changed without doing all
2166 the work to look it up.
2168 Do not try to use named time zones (like "America/Chicago") with dates
2169 very far in the future (thousands of years). The current
2170 implementation of C<DateTime::TimeZone> will use a huge amount of
2171 memory calculating all the DST changes from now until the future
2172 date. Use UTC or the floating time zone and you will be safe.
2178 All constructors can die when invalid parameters are given.
2182 =item * DateTime->new( ... )
2184 This class method accepts parameters for each date and time component:
2185 "year", "month", "day", "hour", "minute", "second", "nanosecond".
2186 It also accepts "locale", "time_zone", and "formatter" parameters.
2188 my $dt = DateTime->new( year => 1066,
2194 nanosecond => 500000000,
2195 time_zone => 'America/Chicago',
2198 DateTime validates the "month", "day", "hour", "minute", and "second",
2199 and "nanosecond" parameters. The valid values for these parameters are:
2209 1-31, and it must be within the valid range of days for the specified
2222 0-61 (to allow for leap seconds). Values of 60 or 61 are only allowed
2223 when they match actual leap seconds.
2233 Invalid parameter types (like an array reference) will cause the
2236 The value for seconds may be from 0 to 61, to account for leap
2237 seconds. If you give a value greater than 59, DateTime does check to
2238 see that it really matches a valid leap second.
2240 All of the parameters are optional except for "year". The "month" and
2241 "day" parameters both default to 1, while the "hour", "minute",
2242 "second", and "nanosecond" parameters all default to 0.
2244 The "locale" parameter should be a string matching one of the valid
2245 locales, or a C<DateTime::Locale> object. See the
2246 L<DateTime::Locale|DateTime::Locale> documentation for details.
2248 The time_zone parameter can be either a scalar or a
2249 C<DateTime::TimeZone> object. A string will simply be passed to the
2250 C<< DateTime::TimeZone->new >> method as its "name" parameter. This
2251 string may be an Olson DB time zone name ("America/Chicago"), an
2252 offset string ("+0630"), or the words "floating" or "local". See the
2253 C<DateTime::TimeZone> documentation for more details.
2255 The default time zone is "floating".
2257 The "formatter" can be either a scalar or an object, but the class
2258 specified by the scalar or the object must implement a
2259 C<format_datetime()> method.
2261 =head4 Parsing Dates
2263 B<This module does not parse dates!> That means there is no
2264 constructor to which you can pass things like "March 3, 1970 12:34".
2266 Instead, take a look at the various C<DateTime::Format::*> modules on
2267 CPAN. These parse all sorts of different date formats, and you're
2268 bound to find something that can handle your particular needs.
2270 =head4 Ambiguous Local Times
2272 Because of Daylight Saving Time, it is possible to specify a local
2273 time that is ambiguous. For example, in the US in 2003, the
2274 transition from to saving to standard time occurred on October 26, at
2275 02:00:00 local time. The local clock changed from 01:59:59 (saving
2276 time) to 01:00:00 (standard time). This means that the hour from
2277 01:00:00 through 01:59:59 actually occurs twice, though the UTC time
2278 continues to move forward.
2280 If you specify an ambiguous time, then the latest UTC time is always
2281 used, in effect always choosing standard time. In this case, you can
2282 simply subtract an hour to the object in order to move to saving time,
2285 # This object represent 01:30:00 standard time
2286 my $dt = DateTime->new( year => 2003,
2292 time_zone => 'America/Chicago',
2295 print $dt->hms; # prints 01:30:00
2297 # Now the object represent 01:30:00 saving time
2298 $dt->subtract( hours => 1 );
2300 print $dt->hms; # still prints 01:30:00
2302 Alternately, you could create the object with the UTC time zone, and
2303 then call the C<set_time_zone()> method to change the time zone. This
2304 is a good way to ensure that the time is not ambiguous.
2306 =head4 Invalid Local Times
2308 Another problem introduced by Daylight Saving Time is that certain
2309 local times just do not exist. For example, in the US in 2003, the
2310 transition from standard to saving time occurred on April 6, at the
2311 change to 2:00:00 local time. The local clock changes from 01:59:59
2312 (standard time) to 03:00:00 (saving time). This means that there is
2313 no 02:00:00 through 02:59:59 on April 6!
2315 Attempting to create an invalid time currently causes a fatal error.
2316 This may change in future version of this module.
2320 =item * DateTime->from_epoch( epoch => $epoch, ... )
2322 This class method can be used to construct a new DateTime object from
2323 an epoch time instead of components. Just as with the C<new()>
2324 method, it accepts "time_zone", "locale", and "formatter" parameters.
2326 If the epoch value is not an integer, the part after the decimal will
2327 be converted to nanoseconds. This is done in order to be compatible
2328 with C<Time::HiRes>. If the floating portion extends past 9 decimal
2329 places, it will be truncated to nine, so that 1.1234567891 will become
2330 1 second and 123,456,789 nanoseconds.
2332 By default, the returned object will be in the UTC time zone.
2334 =item * DateTime->now( ... )
2336 This class method is equivalent to calling C<from_epoch()> with the
2337 value returned from Perl's C<time()> function. Just as with the
2338 C<new()> method, it accepts "time_zone" and "locale" parameters.
2340 By default, the returned object will be in the UTC time zone.
2342 =item * DateTime->today( ... )
2344 This class method is equivalent to:
2346 DateTime->now->truncate( to => 'day' );
2348 =item * DateTime->from_object( object => $object, ... )
2350 This class method can be used to construct a new DateTime object from
2351 any object that implements the C<utc_rd_values()> method. All
2352 C<DateTime::Calendar> modules must implement this method in order to
2353 provide cross-calendar compatibility. This method accepts a
2354 "locale" and "formatter" parameter
2356 If the object passed to this method has a C<time_zone()> method, that
2357 is used to set the time zone of the newly created C<DateTime.pm>
2360 Otherwise, the returned object will be in the floating time zone.
2362 =item * DateTime->last_day_of_month( ... )
2364 This constructor takes the same arguments as can be given to the
2365 C<new()> method, except for "day". Additionally, both "year" and
2366 "month" are required.
2368 =item * DateTime->from_day_of_year( ... )
2370 This constructor takes the same arguments as can be given to the
2371 C<new()> method, except that it does not accept a "month" or "day"
2372 argument. Instead, it requires both "year" and "day_of_year". The
2373 day of year must be between 1 and 366, and 366 is only allowed for
2376 =item * $dt->clone()
2378 This object method returns a new object that is replica of the object
2379 upon which the method is called.
2383 =head3 "Get" Methods
2385 This class has many methods for retrieving information about an
2394 =item * $dt->ce_year()
2396 Returns the year according to the BCE/CE numbering system. The year
2397 before year 1 in this system is year -1, aka "1 BCE".
2399 =item * $dt->era_name()
2401 Returns the long name of the current era, something like "Before
2402 Christ". See the L<Locales|/Locales> section for more details.
2404 =item * $dt->era_abbr()
2406 Returns the abbreviated name of the current era, something like "BC".
2407 See the L<Locales|/Locales> section for more details.
2409 =item * $dt->christian_era()
2411 Returns a string, either "BC" or "AD", according to the year.
2413 =item * $dt->secular_era()
2415 Returns a string, either "BCE" or "CE", according to the year.
2417 =item * $dt->year_with_era()
2419 Returns a string containing the year immediately followed by its era
2420 abbreviation. The year is the absolute value of C<ce_year()>, so that
2421 year 1 is "1AD" and year 0 is "1BC".
2423 =item * $dt->year_with_christian_era()
2425 Like C<year_with_era()>, but uses the christian_era() to get the era
2428 =item * $dt->year_with_secular_era()
2430 Like C<year_with_era()>, but uses the secular_era() method to get the
2433 =item * $dt->month()
2437 Returns the month of the year, from 1..12.
2439 =item * $dt->month_name()
2441 Returns the name of the current month. See the
2442 L<Locales|/Locales> section for more details.
2444 =item * $dt->month_abbr()
2446 Returns the abbreviated name of the current month. See the
2447 L<Locales|/Locales> section for more details.
2449 =item * $dt->day_of_month()
2455 Returns the day of the month, from 1..31.
2457 =item * $dt->day_of_week()
2463 Returns the day of the week as a number, from 1..7, with 1 being
2464 Monday and 7 being Sunday.
2466 =item * $dt->local_day_of_week()
2468 Returns the day of the week as a number, from 1..7. The day
2469 corresponding to 1 will vary based on the locale.
2471 =item * $dt->day_name()
2473 Returns the name of the current day of the week. See the
2474 L<Locales|/Locales> section for more details.
2476 =item * $dt->day_abbr()
2478 Returns the abbreviated name of the current day of the week. See the
2479 L<Locales|/Locales> section for more details.
2481 =item * $dt->day_of_year()
2485 Returns the day of the year.
2487 =item * $dt->quarter()
2489 Returns the quarter of the year, from 1..4.
2491 =item * $dt->quarter_name()
2493 Returns the name of the current quarter. See the
2494 L<Locales|/Locales> section for more details.
2496 =item * $dt->quarter_abbr()
2498 Returns the abbreviated name of the current quarter. See the
2499 L<Locales|/Locales> section for more details.
2501 =item * $dt->day_of_quarter()
2505 Returns the day of the quarter.
2507 =item * $dt->weekday_of_month()
2509 Returns a number from 1..5 indicating which week day of the month this
2510 is. For example, June 9, 2003 is the second Monday of the month, and
2511 so this method returns 2 for that day.
2513 =item * $dt->ymd( $optional_separator ) - also $dt->date(...)
2515 =item * $dt->mdy( $optional_separator )
2517 =item * $dt->dmy( $optional_separator )
2519 Each method returns the year, month, and day, in the order indicated
2520 by the method name. Years are zero-padded to four digits. Months and
2521 days are 0-padded to two digits.
2523 By default, the values are separated by a dash (-), but this can be
2524 overridden by passing a value to the method.
2528 Returns the hour of the day, from 0..23.
2530 =item * $dt->hour_1()
2532 Returns the hour of the day, from 1..24.
2534 =item * $dt->hour_12()
2536 Returns the hour of the day, from 1..12.
2538 =item * $dt->hour_12_0()
2540 Returns the hour of the day, from 0..11.
2542 =item * $dt->am_or_pm()
2544 Returns the appropriate localized abbreviation, depending on the
2547 =item * $dt->minute()
2551 Returns the minute of the hour, from 0..59.
2553 =item * $dt->second()
2557 Returns the second, from 0..61. The values 60 and 61 are used for
2560 =item * $dt->fractional_second()
2562 Returns the second, as a real number from 0.0 until 61.999999999
2564 The values 60 and 61 are used for leap seconds.
2566 =item * $dt->millisecond()
2568 Returns the fractional part of the second as milliseconds (1E-3 seconds).
2570 Half a second is 500 milliseconds.
2572 =item * $dt->microsecond()
2574 Returns the fractional part of the second as microseconds (1E-6
2575 seconds). This value will be rounded to an integer.
2577 Half a second is 500_000 microseconds. This value will be rounded to
2580 =item * $dt->nanosecond()
2582 Returns the fractional part of the second as nanoseconds (1E-9 seconds).
2584 Half a second is 500_000_000 nanoseconds.
2586 =item * $dt->hms( $optional_separator )
2588 =item * $dt->time( $optional_separator )
2590 Returns the hour, minute, and second, all zero-padded to two digits.
2591 If no separator is specified, a colon (:) is used by default.
2593 =item * $dt->datetime()
2595 =item * $dt->iso8601()
2597 This method is equivalent to:
2599 $dt->ymd('-') . 'T' . $dt->hms(':')
2601 =item * $dt->is_leap_year()
2603 This method returns a true or false indicating whether or not the
2604 datetime object is in a leap year.
2608 ($week_year, $week_number) = $dt->week;
2610 Returns information about the calendar week which contains this
2611 datetime object. The values returned by this method are also available
2612 separately through the week_year and week_number methods.
2614 The first week of the year is defined by ISO as the one which contains
2615 the fourth day of January, which is equivalent to saying that it's the
2616 first week to overlap the new year by at least four days.
2618 Typically the week year will be the same as the year that the object
2619 is in, but dates at the very beginning of a calendar year often end up
2620 in the last week of the prior year, and similarly, the final few days
2621 of the year may be placed in the first week of the next year.
2623 =item * $dt->week_year()
2625 Returns the year of the week.
2627 =item * $dt->week_number()
2629 Returns the week of the year, from 1..53.
2631 =item * $dt->week_of_month()
2633 The week of the month, from 0..5. The first week of the month is the
2634 first week that contains a Thursday. This is based on the ICU
2635 definition of week of month, and correlates to the ISO8601 week of
2636 year definition. A day in the week I<before> the week with the first
2637 Thursday will be week 0.
2643 These return the Julian Day and Modified Julian Day, respectively.
2644 The value returned is a floating point number. The fractional portion
2645 of the number represents the time portion of the datetime.
2647 =item * $dt->time_zone()
2649 This returns the C<DateTime::TimeZone> object for the datetime object.
2651 =item * $dt->offset()
2653 This returns the offset from UTC, in seconds, of the datetime object
2654 according to the time zone.
2656 =item * $dt->is_dst()
2658 Returns a boolean indicating whether or not the datetime object is
2659 currently in Daylight Saving Time or not.
2661 =item * $dt->time_zone_long_name()
2663 This is a shortcut for C<< $dt->time_zone->name >>. It's provided so
2664 that one can use "%{time_zone_long_name}" as a strftime format
2667 =item * $dt->time_zone_short_name()
2669 This method returns the time zone abbreviation for the current time
2670 zone, such as "PST" or "GMT". These names are B<not> definitive, and
2671 should not be used in any application intended for general use by
2672 users around the world.
2674 =item * $dt->strftime( $format, ... )
2676 This method implements functionality similar to the C<strftime()>
2677 method in C. However, if given multiple format strings, then it will
2678 return multiple scalars, one for each format string.
2680 See the L<strftime Patterns> section for a list of all possible
2683 If you give a pattern that doesn't exist, then it is simply treated as
2686 =item * $dt->format_cldr( $format, ... )
2688 This method implements formatting based on the CLDR date patterns. If
2689 given multiple format strings, then it will return multiple scalars,
2690 one for each format string.
2692 See the L<CLDR Patterns> section for a list of all possible CLDR
2695 If you give a pattern that doesn't exist, then it is simply treated as
2698 =item * $dt->epoch()
2700 Return the UTC epoch value for the datetime object. Internally, this
2701 is implemented using C<Time::Local>, which uses the Unix epoch even on
2702 machines with a different epoch (such as MacOS). Datetimes before the
2703 start of the epoch will be returned as a negative number.
2705 The return value from this method is always an integer.
2707 Since the epoch does not account for leap seconds, the epoch time for
2708 1972-12-31T23:59:60 (UTC) is exactly the same as that for
2709 1973-01-01T00:00:00.
2711 This module uses C<Time::Local> to calculate the epoch, which may or
2712 may not handle epochs before 1904 or after 2038 (depending on the size
2713 of your system's integers, and whether or not Perl was compiled with
2714 64-bit int support).
2716 =item * $dt->hires_epoch()
2718 Returns the epoch as a floating point number. The floating point
2719 portion of the value represents the nanosecond value of the object.
2720 This method is provided for compatibility with the C<Time::HiRes>
2723 =item * $dt->is_finite()
2725 =item * $dt->is_infinite
2727 These methods allow you to distinguish normal datetime objects from
2728 infinite ones. Infinite datetime objects are documented in
2729 L<DateTime::Infinite|DateTime::Infinite>.
2731 =item * $dt->utc_rd_values()
2733 Returns the current UTC Rata Die days, seconds, and nanoseconds as a
2734 three element list. This exists primarily to allow other calendar
2735 modules to create objects based on the values provided by this object.
2737 =item * $dt->local_rd_values()
2739 Returns the current local Rata Die days, seconds, and nanoseconds as a
2740 three element list. This exists for the benefit of other modules
2741 which might want to use this information for date math, such as
2742 C<DateTime::Event::Recurrence>.
2744 =item * $dt->leap_seconds()
2746 Returns the number of leap seconds that have happened up to the
2747 datetime represented by the object. For floating datetimes, this
2750 =item * $dt->utc_rd_as_seconds()
2752 Returns the current UTC Rata Die days and seconds purely as seconds.
2753 This number ignores any fractional seconds stored in the object,
2754 as well as leap seconds.
2756 =item * $dt->local_rd_as_seconds() - deprecated
2758 Returns the current local Rata Die days and seconds purely as seconds.
2759 This number ignores any fractional seconds stored in the object,
2760 as well as leap seconds.
2762 =item * $dt->locale()
2764 Returns the current locale object.
2766 =item * $dt->formatter()
2768 Returns current formatter object or class. See L<Formatters And
2769 Stringification> for details.
2773 =head3 "Set" Methods
2775 The remaining methods provided by C<DateTime.pm>, except where otherwise
2776 specified, return the object itself, thus making method chaining
2777 possible. For example:
2779 my $dt = DateTime->now->set_time_zone( 'Australia/Sydney' );
2781 my $first = DateTime
2782 ->last_day_of_month( year => 2003, month => 3 )
2784 ->subtract( seconds => 1 );
2788 =item * $dt->set( .. )
2790 This method can be used to change the local components of a date time,
2791 or its locale. This method accepts any parameter allowed by the
2792 C<new()> method except for "time_zone". Time zones may be set using
2793 the C<set_time_zone()> method.
2795 This method performs parameters validation just as is done in the
2798 =item * $dt->set_year()
2800 =item * $dt->set_month()
2802 =item * $dt->set_day()
2804 =item * $dt->set_hour()
2806 =item * $dt->set_minute()
2808 =item * $dt->set_second()
2810 =item * $dt->set_nanosecond()
2812 =item * $dt->set_locale()
2814 These are shortcuts to calling C<set()> with a single key. They all
2815 take a single parameter.
2817 =item * $dt->truncate( to => ... )
2819 This method allows you to reset some of the local time components in
2820 the object to their "zero" values. The "to" parameter is used to
2821 specify which values to truncate, and it may be one of "year",
2822 "month", "week", "day", "hour", "minute", or "second". For example,
2823 if "month" is specified, then the local day becomes 1, and the hour,
2824 minute, and second all become 0.
2826 If "week" is given, then the datetime is set to the beginning of the
2827 week in which it occurs, and the time components are all set to 0.
2829 =item * $dt->set_time_zone( $tz )
2831 This method accepts either a time zone object or a string that can be
2832 passed as the "name" parameter to C<< DateTime::TimeZone->new() >>.
2833 If the new time zone's offset is different from the old time zone,
2834 then the I<local> time is adjusted accordingly.
2838 my $dt = DateTime->new( year => 2000, month => 5, day => 10,
2839 hour => 15, minute => 15,
2840 time_zone => 'America/Los_Angeles', );
2842 print $dt->hour; # prints 15
2844 $dt->set_time_zone( 'America/Chicago' );
2846 print $dt->hour; # prints 17
2848 If the old time zone was a floating time zone, then no adjustments to
2849 the local time are made, except to account for leap seconds. If the
2850 new time zone is floating, then the I<UTC> time is adjusted in order
2851 to leave the local time untouched.
2853 Fans of Tsai Ming-Liang's films will be happy to know that this does
2856 my $dt = DateTime->now( time_zone => 'Asia/Taipei' );
2858 $dt->set_time_zone( 'Europe/Paris' );
2860 Yes, now we can know "ni3 na4 bian1 ji2dian3?"
2862 =item * $dt->set_formatter( $formatter )
2864 Set the formatter for the object. See L<Formatters And
2865 Stringification> for details.
2871 Like the set methods, math related methods always return the object
2872 itself, to allow for chaining:
2874 $dt->add( days => 1 )->subtract( seconds => 1 );
2878 =item * $dt->duration_class()
2880 This returns C<DateTime::Duration>, but exists so that a subclass of
2881 C<DateTime.pm> can provide a different value.
2883 =item * $dt->add_duration( $duration_object )
2885 This method adds a C<DateTime::Duration> to the current datetime. See
2886 the L<DateTime::Duration|DateTime::Duration> docs for more details.
2888 =item * $dt->add( DateTime::Duration->new parameters )
2890 This method is syntactic sugar around the C<add_duration()> method. It
2891 simply creates a new C<DateTime::Duration> object using the parameters
2892 given, and then calls the C<add_duration()> method.
2894 =item * $dt->subtract_duration( $duration_object )
2896 When given a C<DateTime::Duration> object, this method simply calls
2897 C<invert()> on that object and passes that new duration to the
2898 C<add_duration> method.
2900 =item * $dt->subtract( DateTime::Duration->new parameters )
2902 Like C<add()>, this is syntactic sugar for the C<subtract_duration()>
2905 =item * $dt->subtract_datetime( $datetime )
2907 This method returns a new C<DateTime::Duration> object representing
2908 the difference between the two dates. The duration is B<relative> to
2909 the object from which C<$datetime> is subtracted. For example:
2911 2003-03-15 00:00:00.00000000
2912 - 2003-02-15 00:00:00.00000000
2914 -------------------------------
2918 Note that this duration is not an absolute measure of the amount of
2919 time between the two datetimes, because the length of a month varies,
2920 as well as due to the presence of leap seconds.
2922 The returned duration may have deltas for months, days, minutes,
2923 seconds, and nanoseconds.
2925 =item * $dt->delta_md( $datetime )
2927 =item * $dt->delta_days( $datetime )
2929 Each of these methods returns a new C<DateTime::Duration> object
2930 representing some portion of the difference between two datetimes.
2931 The C<delta_md()> method returns a duration which contains only the
2932 month and day portions of the duration is represented. The
2933 C<delta_days()> method returns a duration which contains only days.
2935 The C<delta_md> and C<delta_days> methods truncate the duration so
2936 that any fractional portion of a day is ignored. Both of these
2937 methods operate on the date portion of a datetime only, and so
2938 effectively ignore the time zone.
2940 Unlike the subtraction methods, B<these methods always return a
2941 positive (or zero) duration>.
2943 =item * $dt->delta_ms( $datetime )
2945 Returns a duration which contains only minutes and seconds. Any day
2946 and month differences to minutes are converted to minutes and
2947 seconds. This method also B<always return a positive (or zero)
2950 =item * $dt->subtract_datetime_absolute( $datetime )
2952 This method returns a new C<DateTime::Duration> object representing
2953 the difference between the two dates in seconds and nanoseconds. This
2954 is the only way to accurately measure the absolute amount of time
2955 between two datetimes, since units larger than a second do not
2956 represent a fixed number of seconds.
2960 =head3 Class Methods
2964 =item * DateTime->DefaultLocale( $locale )
2966 This can be used to specify the default locale to be used when
2967 creating DateTime objects. If unset, then "en_US" is used.
2969 =item * DateTime->compare( $dt1, $dt2 )
2971 =item * DateTime->compare_ignore_floating( $dt1, $dt2 )
2973 $cmp = DateTime->compare( $dt1, $dt2 );
2975 $cmp = DateTime->compare_ignore_floating( $dt1, $dt2 );
2977 Compare two DateTime objects. The semantics are compatible with Perl's
2978 C<sort()> function; it returns -1 if $dt1 < $dt2, 0 if $dt1 == $dt2, 1 if $dt1
2981 If one of the two DateTime objects has a floating time zone, it will
2982 first be converted to the time zone of the other object. This is what
2983 you want most of the time, but it can lead to inconsistent results
2984 when you compare a number of DateTime objects, some of which are
2985 floating, and some of which are in other time zones.
2987 If you want to have consistent results (because you want to sort a
2988 number of objects, for example), you can use the
2989 C<compare_ignore_floating()> method:
2991 @dates = sort { DateTime->compare_ignore_floating($a, $b) } @dates;
2993 In this case, objects with a floating time zone will be sorted as if
2994 they were UTC times.
2996 Since DateTime objects overload comparison operators, this:
2998 @dates = sort @dates;
3000 is equivalent to this:
3002 @dates = sort { DateTime->compare($a, $b) } @dates;
3004 DateTime objects can be compared to any other calendar class that
3005 implements the C<utc_rd_values()> method.
3009 =head2 How Datetime Math is Done
3011 It's important to have some understanding of how datetime math is
3012 implemented in order to effectively use this module and
3013 C<DateTime::Duration>.
3015 =head3 Making Things Simple
3017 If you want to simplify your life and not have to think too hard about
3018 the nitty-gritty of datetime math, I have several recommendations:
3022 =item * use the floating time zone
3024 If you do not care about time zones or leap seconds, use the
3025 "floating" timezone:
3027 my $dt = DateTime->now( time_zone => 'floating' );
3029 Math done on two objects in the floating time zone produces very
3030 predictable results.
3032 =item * use UTC for all calculations
3034 If you do care about time zones (particularly DST) or leap seconds,
3035 try to use non-UTC time zones for presentation and user input only.
3036 Convert to UTC immediately and convert back to the local time zone for
3039 my $dt = DateTime->new( %user_input, time_zone => $user_tz );
3040 $dt->set_time_zone('UTC');
3042 # do various operations - store it, retrieve it, add, subtract, etc.
3044 $dt->set_time_zone($user_tz);
3045 print $dt->datetime;
3047 =item * math on non-UTC time zones
3049 If you need to do date math on objects with non-UTC time zones, please
3050 read the caveats below carefully. The results C<DateTime.pm> produces are
3051 predictable and correct, and mostly intuitive, but datetime math gets
3052 very ugly when time zones are involved, and there are a few strange
3053 corner cases involving subtraction of two datetimes across a DST
3056 If you can always use the floating or UTC time zones, you can skip
3057 ahead to L<Leap Seconds and Date Math|Leap Seconds and Date Math>
3059 =item * date vs datetime math
3061 If you only care about the date (calendar) portion of a datetime, you
3062 should use either C<delta_md()> or C<delta_days()>, not
3063 C<subtract_datetime()>. This will give predictable, unsurprising
3064 results, free from DST-related complications.
3066 =item * subtract_datetime() and add_duration()
3068 You must convert your datetime objects to the UTC time zone before
3069 doing date math if you want to make sure that the following formulas
3076 Note that using C<delta_days> ensures that this formula always works,
3077 regardless of the timezone of the objects involved, as does using
3078 C<subtract_datetime_absolute()>. Other methods of subtraction are not
3083 =head3 Adding a Duration to a Datetime
3085 The parts of a duration can be broken down into five parts. These are
3086 months, days, minutes, seconds, and nanoseconds. Adding one month to
3087 a date is different than adding 4 weeks or 28, 29, 30, or 31 days.
3088 Similarly, due to DST and leap seconds, adding a day can be different
3089 than adding 86,400 seconds, and adding a minute is not exactly the
3092 We cannot convert between these units, except for seconds and
3093 nanoseconds, because there is no fixed conversion between the two
3094 units, because of things like leap seconds, DST changes, etc.
3096 C<DateTime.pm> always adds (or subtracts) days, then months, minutes, and then
3097 seconds and nanoseconds. If there are any boundary overflows, these are
3098 normalized at each step. For the days and months the local (not UTC) values
3099 are used. For minutes and seconds, the local values are used. This generally
3102 This means that adding one month and one day to February 28, 2003 will
3103 produce the date April 1, 2003, not March 29, 2003.
3105 my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
3107 $dt->add( months => 1, days => 1 );
3109 # 2003-04-01 - the result
3111 On the other hand, if we add months first, and then separately add
3112 days, we end up with March 29, 2003:
3114 $dt->add( months => 1 )->add( days => 1 );
3118 We see similar strangeness when math crosses a DST boundary:
3120 my $dt = DateTime->new( year => 2003, month => 4, day => 5,
3121 hour => 1, minute => 58,
3122 time_zone => "America/Chicago",
3125 $dt->add( days => 1, minutes => 3 );
3126 # 2003-04-06 02:01:00
3128 $dt->add( minutes => 3 )->add( days => 1 );
3129 # 2003-04-06 03:01:00
3131 Note that if you converted the datetime object to UTC first you would
3132 get predictable results.
3134 If you want to know how many seconds a duration object represents, you
3135 have to add it to a datetime to find out, so you could do:
3137 my $now = DateTime->now( time_zone => 'UTC' );
3138 my $later = $now->clone->add_duration($duration);
3140 my $seconds_dur = $later->subtract_datetime_absolute($now);
3142 This returns a duration which only contains seconds and nanoseconds.
3144 If we were add the duration to a different datetime object we might
3145 get a different number of seconds.
3147 If you need to do lots of work with durations, take a look at Rick
3148 Measham's C<DateTime::Format::Duration> module, which lets you present
3149 information from durations in many useful ways.
3151 There are other subtract/delta methods in DateTime.pm to generate
3152 different types of durations. These methods are
3153 C<subtract_datetime()>, C<subtract_datetime_absolute()>,
3154 C<delta_md()>, C<delta_days()>, and C<delta_ms()>.
3156 =head3 Datetime Subtraction
3158 Date subtraction is done solely based on the two object's local
3159 datetimes, with one exception to handle DST changes. Also, if the two
3160 datetime objects are in different time zones, one of them is converted
3161 to the other's time zone first before subtraction. This is best
3162 explained through examples:
3164 The first of these probably makes the most sense:
3166 my $dt1 = DateTime->new( year => 2003, month => 5, day => 6,
3167 time_zone => 'America/Chicago',
3171 my $dt2 = DateTime->new( year => 2003, month => 11, day => 6,
3172 time_zone => 'America/Chicago',
3176 my $dur = $dt2->subtract_datetime($dt1);
3181 This one is a little trickier, but still fairly logical:
3183 my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
3184 hour => 1, minute => 58,
3185 time_zone => "America/Chicago",
3189 my $dt2 = DateTime->new( year => 2003, month => 4, day => 7,
3190 hour => 2, minute => 1,
3191 time_zone => "America/Chicago",
3195 my $dur = $dt2->subtract_datetime($dt1);
3196 # 2 days and 3 minutes
3198 Which contradicts the result this one gives, even though they both
3201 my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
3202 hour => 1, minute => 58,
3203 time_zone => "America/Chicago",
3207 my $dt2 = DateTime->new( year => 2003, month => 4, day => 6,
3208 hour => 3, minute => 1,
3209 time_zone => "America/Chicago",
3213 my $dur = $dt2->subtract_datetime($dt1);
3214 # 1 day and 3 minutes
3216 This last example illustrates the "DST" exception mentioned earlier.
3217 The exception accounts for the fact 2003-04-06 only lasts 23 hours.
3221 my $dt2 = DateTime->new( year => 2003, month => 10, day => 26,
3223 time_zone => 'America/Chicago',
3226 my $dt1 = $dt2->clone->subtract( hours => 1 );
3228 my $dur = $dt2->subtract_datetime($dt1);
3231 This seems obvious until you realize that subtracting 60 minutes from
3232 C<$dt2> in the above example still leaves the clock time at
3233 "01:00:00". This time we are accounting for a 25 hour day.
3235 =head3 Reversibility
3237 Date math operations are not always reversible. This is because of
3238 the way that addition operations are ordered. As was discussed
3239 earlier, adding 1 day and 3 minutes in one call to C<add()> is not the
3240 same as first adding 3 minutes and 1 day in two separate calls.
3242 If we take a duration returned from C<subtract_datetime()> and then
3243 try to add or subtract that duration from one of the datetimes we just
3244 used, we sometimes get interesting results:
3246 my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
3247 hour => 1, minute => 58,
3248 time_zone => "America/Chicago",
3251 my $dt2 = DateTime->new( year => 2003, month => 4, day => 6,
3252 hour => 3, minute => 1,
3253 time_zone => "America/Chicago",
3256 my $dur = $dt2->subtract_datetime($dt1);
3257 # 1 day and 3 minutes
3259 $dt1->add_duration($dur);
3262 $dt2->subtract_duration($dur);
3263 # gives us 2003-04-05 02:58:00 - 1 hour later than $dt1
3265 The C<subtract_dauration()> operation gives us a (perhaps) unexpected
3266 answer because it first subtracts one day to get 2003-04-05T03:01:00
3267 and then subtracts 3 minutes to get the final result.
3269 If we explicitly reverse the order we can get the original value of
3270 C<$dt1>. This can be facilitated by C<DateTime::Duration>'s
3271 C<calendar_duration()> and C<clock_duration()> methods:
3273 $dt2->subtract_duration( $dur->clock_duration )
3274 ->subtract_duration( $dur->calendar_duration );
3276 =head3 Leap Seconds and Date Math
3278 The presence of leap seconds can cause even more anomalies in date
3279 math. For example, the following is a legal datetime:
3281 my $dt = DateTime->new( year => 1972, month => 12, day => 31,
3282 hour => 23, minute => 59, second => 60,
3283 time_zone => 'UTC' );
3285 If we do the following:
3287 $dt->add( months => 1 );
3289 Then the datetime is now "1973-02-01 00:00:00", because there is no
3290 23:59:60 on 1973-01-31.
3292 Leap seconds also force us to distinguish between minutes and seconds
3293 during date math. Given the following datetime:
3295 my $dt = DateTime->new( year => 1972, month => 12, day => 31,
3296 hour => 23, minute => 59, second => 30,
3297 time_zone => 'UTC' );
3299 we will get different results when adding 1 minute than we get if we
3300 add 60 seconds. This is because in this case, the last minute of the
3301 day, beginning at 23:59:00, actually contains 61 seconds.
3303 Here are the results we get:
3305 # 1972-12-31 23:59:30 - our starting datetime
3307 $dt->clone->add( minutes => 1 );
3308 # 1973-01-01 00:00:30 - one minute later
3310 $dt->clone->add( seconds => 60 );
3311 # 1973-01-01 00:00:29 - 60 seconds later
3313 $dt->clone->add( seconds => 61 );
3314 # 1973-01-01 00:00:30 - 61 seconds later
3316 =head3 Local vs. UTC and 24 hours vs. 1 day
3318 When math crosses a daylight saving boundary, a single day may have
3319 more or less than 24 hours.
3321 For example, if you do this:
3323 my $dt = DateTime->new( year => 2003, month => 4, day => 5,
3325 time_zone => 'America/Chicago',
3327 $dt->add( days => 1 );
3329 then you will produce an I<invalid> local time, and therefore an
3330 exception will be thrown.
3332 However, this works:
3334 my $dt = DateTime->new( year => 2003, month => 4, day => 5,
3336 time_zone => 'America/Chicago',
3338 $dt->add( hours => 24 );
3340 and produces a datetime with the local time of "03:00".
3342 If all this makes your head hurt, there is a simple alternative. Just
3343 convert your datetime object to the "UTC" time zone before doing date
3344 math on it, and switch it back to the local time zone afterwards.
3345 This avoids the possibility of having date math throw an exception,
3346 and makes sure that 1 day equals 24 hours. Of course, this may not
3347 always be desirable, so caveat user!
3351 This module explicitly overloads the addition (+), subtraction (-),
3352 string and numeric comparison operators. This means that the
3353 following all do sensible things:
3355 my $new_dt = $dt + $duration_obj;
3357 my $new_dt = $dt - $duration_obj;
3359 my $duration_obj = $dt - $new_dt;
3361 foreach my $dt ( sort @dts ) { ... }
3363 Additionally, the fallback parameter is set to true, so other
3364 derivable operators (+=, -=, etc.) will work properly. Do not expect
3365 increment (++) or decrement (--) to do anything useful.
3367 If you attempt to sort DateTime objects with non-DateTime.pm objects
3368 or scalars (strings, number, whatever) then an exception will be
3369 thrown. Using the string comparison operators, C<eq> or C<ne>, to
3370 compare a DateTime.pm always returns false.
3372 The module also overloads stringification to use the C<iso8601()>
3375 =head2 Formatters And Stringification
3377 You can optionally specify a "formatter", which is usually a
3378 DateTime::Format::* object/class, to control the stringification of
3379 the DateTime object.
3381 Any of the constructor methods can accept a formatter argument:
3383 my $formatter = DateTime::Format::Strptime->new(...);
3384 my $dt = DateTime->new(year => 2004, formatter => $formatter);
3386 Or, you can set it afterwards:
3388 $dt->set_formatter($formatter);
3389 $formatter = $dt->formatter();
3391 Once you set the formatter, the overloaded stringification method will
3392 use the formatter. If unspecified, the C<iso8601()> method is used.
3394 A formatter can be handy when you know that in your application you
3395 want to stringify your DateTime objects into a special format all the
3396 time, for example to a different language.
3398 If you provide a formatter class name or object, it must implement a
3399 C<format_datetime> method. This method will be called with just the
3400 DateTime object as its argument.
3402 =head2 strftime Patterns
3404 The following patterns are allowed in the format string given to the
3405 C<< $dt->strftime() >> method:
3411 The abbreviated weekday name.
3415 The full weekday name.
3419 The abbreviated month name.
3423 The full month name.
3427 The default datetime format for the object's locale.
3431 The century number (year/100) as a 2-digit integer.
3435 The day of the month as a decimal number (range 01 to 31).
3439 Equivalent to %m/%d/%y. This is not a good standard format if you
3440 want folks from both the United States and the rest of the world to
3441 understand the date!
3445 Like %d, the day of the month as a decimal number, but a leading zero
3446 is replaced by a space.
3450 Equivalent to %Y-%m-%d (the ISO 8601 date format)
3454 The ISO 8601 year with century as a decimal number. The 4-digit year
3455 corresponding to the ISO week number (see %V). This has the same
3456 format and value as %Y, except that if the ISO week number belongs to
3457 the previous or next year, that year is used instead. (TZ)
3461 Like %G, but without century, i.e., with a 2-digit year (00-99).
3469 The hour as a decimal number using a 24-hour clock (range 00 to 23).
3473 The hour as a decimal number using a 12-hour clock (range 01 to 12).
3477 The day of the year as a decimal number (range 001 to 366).
3481 The hour (24-hour clock) as a decimal number (range 0 to 23); single
3482 digits are preceded by a blank. (See also %H.)
3486 The hour (12-hour clock) as a decimal number (range 1 to 12); single
3487 digits are preceded by a blank. (See also %I.)
3491 The month as a decimal number (range 01 to 12).
3495 The minute as a decimal number (range 00 to 59).
3499 A newline character.
3503 The fractional seconds digits. Default is 9 digits (nanoseconds).
3505 %3N milliseconds (3 digits)
3506 %6N microseconds (6 digits)
3507 %9N nanoseconds (9 digits)
3511 Either `AM' or `PM' according to the given time value, or the
3512 corresponding strings for the current locale. Noon is treated as `pm'
3513 and midnight as `am'.
3517 Like %p but in lowercase: `am' or `pm' or a corresponding string for
3522 The time in a.m. or p.m. notation. In the POSIX locale this is
3523 equivalent to `%I:%M:%S %p'.
3527 The time in 24-hour notation (%H:%M). (SU) For a version including the
3528 seconds, see %T below.
3532 The number of seconds since the epoch.
3536 The second as a decimal number (range 00 to 61).
3544 The time in 24-hour notation (%H:%M:%S).
3548 The day of the week as a decimal, range 1 to 7, Monday being 1. See
3553 The week number of the current year as a decimal number, range 00 to
3554 53, starting with the first Sunday as the first day of week 01. See
3559 The ISO 8601:1988 week number of the current year as a decimal number,
3560 range 01 to 53, where week 1 is the first week that has at least 4
3561 days in the current year, and with Monday as the first day of the
3562 week. See also %U and %W.
3566 The day of the week as a decimal, range 0 to 6, Sunday being 0. See
3571 The week number of the current year as a decimal number, range 00 to
3572 53, starting with the first Monday as the first day of week 01.
3576 The default date format for the object's locale.
3580 The default time format for the object's locale.
3584 The year as a decimal number without a century (range 00 to 99).
3588 The year as a decimal number including the century.
3592 The time-zone as hour offset from UTC. Required to emit
3593 RFC822-conformant dates (using "%a, %d %b %Y %H:%M:%S %z").
3597 The time zone or name or abbreviation.
3601 A literal `%' character.
3605 Any method name may be specified using the format C<%{method}> name
3606 where "method" is a valid C<DateTime.pm> object method.
3610 =head2 CLDR Patterns
3612 The CLDR pattern language is both more powerful and more complex than
3613 strftime. Unlike strftime patterns, you often have to explicitly
3614 escape text that you do not want formatted, as the patterns are simply
3615 letters without any prefix.
3617 For example, "yyyy-MM-dd" is a valid CLDR pattern. If you want to
3618 include any lower or upper case ASCII characters as-is, you can
3619 surround them with single quotes ('). If you want to include a single
3620 quote, you must escape it as two single quotes ('').
3623 'It is now' h 'o''clock' a
3625 Spaces and any non-letter text will always be passed through as-is.
3627 Many CLDR patterns which produce numbers will pad the number with
3628 leading zeroes depending on the length of the format specifier. For
3629 example, "h" represents the current hour from 1-12. If you specify
3630 "hh" then the 1-9 will have a leading zero prepended.
3632 However, CLDR often uses five of a letter to represent the narrow form
3633 of a pattern. This inconsistency is necessary for backwards
3636 CLDR often distinguishes between the "format" and "stand-alone" forms
3637 of a pattern. The format pattern is used when the thing in question is
3638 being placed into a larger string. The stand-alone form is used when
3639 displaying that item by itself, for example in a calendar.
3641 It also often provides three sizes for each item, wide (the full
3642 name), abbreviated, and narrow. The narrow form is often just a single
3643 character, for example "T" for "Tuesday", and may not be unique.
3645 CLDR provides a fairly complex system for localizing time zones that
3646 we ignore entirely. The time zone patterns just use the information
3647 provided by C<DateTime::TimeZone>, and I<do not follow the CLDR spec>.
3649 The output of a CLDR pattern is always localized, when applicable.
3651 CLDR provides the following patterns:
3657 The abbreviated era (BC, AD).
3661 The wide era (Before Christ, Anno Domini).
3665 The narrow era, if it exists (and it mostly doesn't).
3669 The year, zero-prefixed as needed. Negative years will start with a "-",
3670 and this will be included in the length calculation.
3672 In other, words the "yyyyy" pattern will format year -1234 as "-1234", not
3677 This is a special case. It always produces a two-digit year, so "1976" becomes
3678 "76". Negative years will start with a "-", making them one character longer.
3682 The week of the year, from C<< $dt->week_year() >>.
3686 Same as "y" except that "uu" is not a special case.
3690 The quarter as a number (1..4).
3694 The abbreviated format form for the quarter.
3698 The wide format form for the quarter.
3702 The quarter as a number (1..4).
3706 The abbreviated stand-alone form for the quarter.
3710 The wide stand-alone form for the quarter.
3714 The numerical month.
3718 The abbreviated format form for the month.
3722 The wide format form for the month.
3726 The narrow format form for the month.
3730 The numerical month.
3734 The abbreviated stand-alone form for the month.
3738 The wide stand-alone form for the month.
3742 The narrow stand-alone form for the month.
3746 The week of the year, from C<< $dt->week_number() >>.
3750 The week of the month, from C<< $dt->week_of_month() >>.
3754 The numeric day of of the month.
3758 The numeric day of of the year.
3762 The day of the week in the month, from C<< $dt->weekday_of_month() >>.
3766 The modified Julian day, from C<< $dt->mjd() >>.
3768 =item * E{1,3} and eee
3770 The abbreviated format form for the day of the week.
3772 =item * EEEE and eeee
3774 The wide format form for the day of the week.
3776 =item * EEEEE and eeeee
3778 The narrow format form for the day of the week.
3782 The I<local> numeric day of the week, from 1 to 7. This number depends
3783 on what day is considered the first day of the week, which varies by
3784 locale. For example, in the US, Sunday is the first day of the week,
3785 so this returns 2 for Monday.
3789 The numeric day of the week from 1 to 7, treating Monday as the first
3790 of the week, regardless of locale.
3794 The abbreviated stand-alone form for the day of the week.
3798 The wide stand-alone form for the day of the week.
3802 The narrow format form for the day of the week.
3806 The localized form of AM or PM for the time.
3826 The hour, in 12 or 24 hour form, based on the preferred form for the
3827 locale. In other words, this is equivalent to either "h{1,2}" or
3840 The fractional portion of the seconds, rounded based on the length of
3841 the specifier. This returned I<without> a leading decimal point, but
3842 may have leading or trailing zeroes.
3846 The millisecond of the day, based on the current time. In other words,
3847 if it is 12:00:00.00, this returns 43200000.
3851 The time zone short name.
3855 The time zone long name.
3859 The time zone short name and the offset as one string, so something
3864 The time zone long name.
3868 The time zone short name.
3872 The time zone long name.
3876 The time zone short name.
3880 The time zone long name.
3884 =head1 DateTime.pm and Storable
3886 DateTime implements Storable hooks in order to reduce the size of a
3887 serialized DateTime object.
3891 The tests in F<20infinite.t> seem to fail on some machines,
3892 particularly on Win32. This appears to be related to Perl's internal
3893 handling of IEEE infinity and NaN, and seems to be highly
3894 platform/compiler/phase of moon dependent.
3896 If you don't plan to use infinite datetimes you can probably ignore
3897 this. This will be fixed (somehow) in future versions.
3901 Support for this module is provided via the datetime@perl.org email
3902 list. See http://datetime.perl.org/?MailingList for details.
3904 Please submit bugs to the CPAN RT system at
3905 http://rt.cpan.org/NoAuth/ReportBug.html?Queue=datetime or via email
3906 at bug-datetime@rt.cpan.org.
3910 If you'd like to thank me for the work I've done on this module,
3911 please consider making a "donation" to me via PayPal. I spend a lot of
3912 free time creating free software, and would appreciate any support
3913 you'd care to offer.
3915 Please note that B<I am not suggesting that you must do this> in order
3916 for me to continue working on this particular software. I will
3917 continue to do so, inasmuch as I have in the past, for as long as it
3920 Similarly, a donation made in this way will probably not make me work
3921 on this software much more, unless I get so many donations that I can
3922 consider working on free software full time, which seems unlikely at
3925 To donate, log into PayPal and send money to autarch@urth.org or use
3926 the button on this page:
3927 L<http://www.urth.org/~autarch/fs-donation.html>
3931 Dave Rolsky <autarch@urth.org>
3933 However, please see the CREDITS file for more details on who I really
3934 stole all the code from.
3938 Copyright (c) 2003-2009 David Rolsky. All rights reserved. This
3939 program is free software; you can redistribute it and/or modify it
3940 under the same terms as Perl itself.
3942 Portions of the code in this distribution are derived from other
3943 works. Please see the CREDITS file for more details.
3945 The full text of the license can be found in the LICENSE file included
3950 datetime@perl.org mailing list
3952 http://datetime.perl.org/