Add built local::lib
[catagits/Gitalist.git] / local-lib5 / lib / perl5 / i486-linux-gnu-thread-multi / DateTime.pm
1 package DateTime;
2
3 use 5.006;
4
5 use strict;
6 use warnings;
7
8 use Carp;
9 use DateTime::Helpers;
10
11 our $VERSION;
12
13 BEGIN
14 {
15     $VERSION = '0.53';
16
17     my $loaded = 0;
18     unless ( $ENV{PERL_DATETIME_PP} )
19     {
20         local $@;
21         eval
22         {
23             require XSLoader;
24             XSLoader::load( 'DateTime', $DateTime::VERSION );
25
26             $DateTime::IsPurePerl = 0;
27         };
28
29         die $@ if $@ && $@ !~ /object version|loadable object/;
30
31         $loaded = 1 unless $@;
32     }
33
34     if ($loaded)
35     {
36         require DateTimePPExtra
37             unless defined &DateTime::_normalize_tai_seconds;
38     }
39     else
40     {
41         require DateTimePP;
42     }
43 }
44
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 );
50
51 # for some reason, overloading doesn't work unless fallback is listed
52 # early.
53 #
54 # 3rd parameter ( $_[2] ) means the parameters are 'reversed'.
55 # see: "Calling conventions for binary operations" in overload docs.
56 #
57 use overload ( 'fallback' => 1,
58                '<=>' => '_compare_overload',
59                'cmp' => '_compare_overload',
60                '""'  => '_stringify',
61                '-'   => '_subtract_overload',
62                '+'   => '_add_overload',
63                'eq'  => '_string_equals_overload',
64                'ne'  => '_string_not_equals_overload',
65              );
66
67 # Have to load this after overloading is defined, after BEGIN blocks
68 # or else weird crashes ensue
69 require DateTime::Infinite;
70
71 use constant MAX_NANOSECONDS => 1_000_000_000;  # 1E9 = almost 32 bits
72
73 use constant INFINITY     =>      (9 ** 9 ** 9);
74 use constant NEG_INFINITY => -1 * (9 ** 9 ** 9);
75 use constant NAN          => INFINITY - INFINITY;
76
77 use constant SECONDS_PER_DAY => 86400;
78
79 use constant duration_class => 'DateTime::Duration';
80
81 my( @MonthLengths, @LeapYearMonthLengths );
82
83 BEGIN
84 {
85     @MonthLengths =
86         ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
87
88     @LeapYearMonthLengths = @MonthLengths;
89     $LeapYearMonthLengths[1]++;
90 }
91
92 {
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!
96     my $DefaultLocale;
97     sub DefaultLocale
98     {
99         my $class = shift;
100
101         if (@_)
102         {
103             my $lang = shift;
104
105             DateTime::Locale->load($lang);
106
107             $DefaultLocale = $lang;
108         }
109
110         return $DefaultLocale;
111     }
112     # backwards compat
113     *DefaultLanguage = \&DefaultLocale;
114 }
115 __PACKAGE__->DefaultLocale('en_US');
116
117 my $BasicValidate =
118     { year   => { type => SCALAR,
119                   callbacks =>
120                   { 'is an integer' =>
121                     sub { $_[0] =~ /^-?\d+$/ }
122                   },
123                 },
124       month  => { type => SCALAR, default => 1,
125                   callbacks =>
126                   { 'an integer between 1 and 12' =>
127                     sub { $_[0] =~ /^\d+$/ && $_[0] >= 1 && $_[0] <= 12 }
128                   },
129                 },
130       day    => { type => SCALAR, default => 1,
131                   callbacks =>
132                   { 'an integer which is a possible valid day of month' =>
133                     sub { $_[0] =~ /^\d+$/ && $_[0] >= 1 && $_[0] <= 31 }
134                   },
135                 },
136       hour   => { type => SCALAR, default => 0,
137                   callbacks =>
138                   { 'an integer between 0 and 23' =>
139                     sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 && $_[0] <= 23 },
140                   },
141                 },
142       minute => { type => SCALAR, default => 0,
143                   callbacks =>
144                   { 'an integer between 0 and 59' =>
145                     sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 && $_[0] <= 59 },
146                   },
147                 },
148       second => { type => SCALAR, default => 0,
149                   callbacks =>
150                   { 'an integer between 0 and 61' =>
151                     sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 && $_[0] <= 61 },
152                   },
153                 },
154       nanosecond => { type => SCALAR, default => 0,
155                       callbacks =>
156                       { 'a positive integer' =>
157                         sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 },
158                       }
159                     },
160       locale    => { type => SCALAR | OBJECT,
161                      default => undef },
162       language  => { type => SCALAR | OBJECT,
163                      optional => 1 },
164     };
165
166 my $NewValidate =
167     { %$BasicValidate,
168       time_zone => { type => SCALAR | OBJECT,
169                      default => 'floating' },
170       formatter => { type => SCALAR | OBJECT, can => 'format_datetime', optional => 1 },
171     };
172
173 sub new
174 {
175     my $class = shift;
176     my %p = validate( @_, $NewValidate );
177
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} );
180
181     my $self = bless {}, $class;
182
183     $p{locale} = delete $p{language} if exists $p{language};
184     $p{locale} = $class->DefaultLocale unless defined $p{locale};
185
186     if ( ref $p{locale} )
187     {
188         $self->{locale} = $p{locale};
189     }
190     else
191     {
192         $self->{locale} = DateTime::Locale->load( $p{locale} );
193     }
194
195     $self->{tz} =
196         ( ref $p{time_zone} ?
197           $p{time_zone} :
198           DateTime::TimeZone->new( name => $p{time_zone} )
199         );
200
201     $self->{local_rd_days} =
202         $class->_ymd2rd( @p{ qw( year month day ) } );
203
204     $self->{local_rd_secs} =
205         $class->_time_as_seconds( @p{ qw( hour minute second ) } );
206
207     $self->{offset_modifier} = 0;
208
209     $self->{rd_nanosecs} = $p{nanosecond};
210     $self->{formatter} = $p{formatter};
211
212     $self->_normalize_nanoseconds( $self->{local_rd_secs}, $self->{rd_nanosecs} );
213
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;
221
222     $self->_calc_utc_rd;
223
224     $self->_handle_offset_modifier( $p{second} );
225
226     $self->_calc_local_rd;
227
228     if ( $p{second} > 59 )
229     {
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
234                <
235                $p{second} - 59 )
236            )
237         {
238             Carp::croak( "Invalid second value ($p{second})\n" );
239         }
240     }
241
242     return $self;
243 }
244
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().
247 sub _new_from_self
248 {
249     my $self = shift;
250
251     my %old = map { $_ => $self->$_() }
252         qw( year month day hour minute second nanosecond
253             locale time_zone );
254     $old{formatter} = $self->formatter()
255         if defined $self->formatter();
256
257     return (ref $self)->new( %old, @_ );
258 }
259
260 sub _handle_offset_modifier
261 {
262     my $self = shift;
263
264     $self->{offset_modifier} = 0;
265
266     return if $self->{tz}->is_floating;
267
268     my $second = shift;
269     my $utc_is_valid = shift;
270
271     my $utc_rd_days = $self->{utc_rd_days};
272
273     my $offset = $utc_is_valid ? $self->offset : $self->_offset_for_local_datetime;
274
275     if ( $offset >= 0
276          && $self->{local_rd_secs} >= $offset
277        )
278     {
279         if ( $second < 60 && $offset > 0 )
280         {
281             $self->{offset_modifier} =
282                 $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
283
284             $self->{local_rd_secs} += $self->{offset_modifier};
285         }
286         elsif ( $second == 60
287                 &&
288                 ( ( $self->{local_rd_secs} == $offset
289                     && $offset > 0 )
290                   ||
291                   ( $offset == 0
292                     && $self->{local_rd_secs} > 86399 ) )
293               )
294         {
295             my $mod = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
296
297             unless ( $mod == 0 )
298             {
299                 $self->{utc_rd_secs} -= $mod;
300
301                 $self->_normalize_seconds;
302             }
303         }
304     }
305     elsif ( $offset < 0
306             && $self->{local_rd_secs} >= SECONDS_PER_DAY + $offset )
307     {
308         if ( $second < 60 )
309         {
310             $self->{offset_modifier} =
311                 $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
312
313             $self->{local_rd_secs} += $self->{offset_modifier};
314         }
315         elsif ( $second == 60 && $self->{local_rd_secs} == SECONDS_PER_DAY + $offset )
316         {
317             my $mod = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
318
319             unless ( $mod == 0 )
320             {
321                 $self->{utc_rd_secs} -= $mod;
322
323                 $self->_normalize_seconds;
324             }
325         }
326     }
327 }
328
329 sub _calc_utc_rd
330 {
331     my $self = shift;
332
333     delete $self->{utc_c};
334
335     if ( $self->{tz}->is_utc || $self->{tz}->is_floating )
336     {
337         $self->{utc_rd_days} = $self->{local_rd_days};
338         $self->{utc_rd_secs} = $self->{local_rd_secs};
339     }
340     else
341     {
342         my $offset = $self->_offset_for_local_datetime;
343
344         $offset += $self->{offset_modifier};
345
346         $self->{utc_rd_days} = $self->{local_rd_days};
347         $self->{utc_rd_secs} = $self->{local_rd_secs} - $offset;
348     }
349
350     # We account for leap seconds in the new() method and nowhere else
351     # except date math.
352     $self->_normalize_tai_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} );
353 }
354
355 sub _normalize_seconds
356 {
357     my $self = shift;
358
359     return if $self->{utc_rd_secs} >= 0 && $self->{utc_rd_secs} <= 86399;
360
361     if ( $self->{tz}->is_floating )
362     {
363         $self->_normalize_tai_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} );
364     }
365     else
366     {
367         $self->_normalize_leap_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} );
368     }
369 }
370
371 sub _calc_local_rd
372 {
373     my $self = shift;
374
375     delete $self->{local_c};
376
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 )
380     {
381         $self->{local_rd_days} = $self->{utc_rd_days};
382         $self->{local_rd_secs} = $self->{utc_rd_secs};
383     }
384     else
385     {
386         my $offset = $self->offset;
387
388         $self->{local_rd_days} = $self->{utc_rd_days};
389         $self->{local_rd_secs} = $self->{utc_rd_secs} + $offset;
390
391         # intentionally ignore leap seconds here
392         $self->_normalize_tai_seconds( $self->{local_rd_days}, $self->{local_rd_secs} );
393
394         $self->{local_rd_secs} += $self->{offset_modifier};
395     }
396
397     $self->_calc_local_components;
398 }
399
400 sub _calc_local_components
401 {
402     my $self = shift;
403
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 );
407
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} );
411 }
412
413 sub _calc_utc_components
414 {
415     my $self = shift;
416
417     die "Cannot get UTC components before UTC RD has been calculated\n"
418         unless defined $self->{utc_rd_days};
419
420     @{ $self->{utc_c} }{ qw( year month day ) } =
421         $self->_rd2ymd( $self->{utc_rd_days} );
422
423     @{ $self->{utc_c} }{ qw( hour minute second ) } =
424         $self->_seconds_as_components( $self->{utc_rd_secs} );
425 }
426
427 sub _utc_ymd
428 {
429     my $self = shift;
430
431     $self->_calc_utc_components unless exists $self->{utc_c}{year};
432
433     return @{ $self->{utc_c} }{ qw( year month day ) };
434 }
435
436 sub _utc_hms
437 {
438     my $self = shift;
439
440     $self->_calc_utc_components unless exists $self->{utc_c}{hour};
441
442     return @{ $self->{utc_c} }{ qw( hour minute second ) };
443 }
444
445 {
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',
451                                  optional => 1 },
452                };
453
454     sub from_epoch
455     {
456         my $class = shift;
457         my %p = validate( @_, $spec );
458
459         my %args;
460
461         # Because epoch may come from Time::HiRes
462         my $fraction = $p{epoch} - int( $p{epoch} );
463         $args{nanosecond} = int( $fraction * MAX_NANOSECONDS )
464             if $fraction;
465
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 ];
470         $args{year} += 1900;
471         $args{month}++;
472
473         my $self = $class->new( %p, %args, time_zone => 'UTC' );
474
475         $self->set_time_zone( $p{time_zone} ) if exists $p{time_zone};
476
477         return $self;
478     }
479 }
480
481 # use scalar time in case someone's loaded Time::Piece
482 sub now { shift->from_epoch( epoch => (scalar time), @_ ) }
483
484 sub today { shift->now(@_)->truncate( to => 'day' ) }
485
486 {
487     my $spec = { object => { type => OBJECT,
488                              can => 'utc_rd_values',
489                            },
490                  locale     => { type => SCALAR | OBJECT, optional => 1 },
491                  language   => { type => SCALAR | OBJECT, optional => 1 },
492                  formatter  => { type => SCALAR | OBJECT, can => 'format_datetime',
493                                  optional => 1 },
494                };
495
496     sub from_object
497     {
498         my $class = shift;
499         my %p = validate( @_, $spec );
500
501         my $object = delete $p{object};
502
503         my ( $rd_days, $rd_secs, $rd_nanosecs ) = $object->utc_rd_values;
504
505         # A kludge because until all calendars are updated to return all
506         # three values, $rd_nanosecs could be undef
507         $rd_nanosecs ||= 0;
508
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) )
515         {
516             $leap_seconds = $rd_secs - 86399;
517             $rd_secs -= $leap_seconds;
518         }
519
520         my %args;
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;
525
526         $args{second} += $leap_seconds;
527
528         my $new = $class->new( %p, %args, time_zone => 'UTC' );
529
530         if ( $object->can('time_zone') )
531         {
532             $new->set_time_zone( $object->time_zone );
533         }
534         else
535         {
536             $new->set_time_zone( 'floating' );
537         }
538
539         return $new;
540     }
541 }
542
543 my $LastDayOfMonthValidate = { %$NewValidate };
544 foreach ( keys %$LastDayOfMonthValidate )
545 {
546     my %copy = %{ $LastDayOfMonthValidate->{$_} };
547
548     delete $copy{default};
549     $copy{optional} = 1 unless $_ eq 'year' || $_ eq 'month';
550
551     $LastDayOfMonthValidate->{$_} = \%copy;
552 }
553
554 sub last_day_of_month
555 {
556     my $class = shift;
557     my %p = validate( @_, $LastDayOfMonthValidate );
558
559     my $day = $class->_month_length( $p{year}, $p{month} );
560
561     return $class->new( %p, day => $day );
562 }
563
564 sub _month_length
565 {
566     return ( $_[0]->_is_leap_year( $_[1] ) ?
567              $LeapYearMonthLengths[ $_[2] - 1 ] :
568              $MonthLengths[ $_[2] - 1 ]
569            );
570 }
571
572 my $FromDayOfYearValidate = { %$NewValidate };
573 foreach ( keys %$FromDayOfYearValidate )
574 {
575     next if $_ eq 'month' || $_ eq 'day';
576
577     my %copy = %{ $FromDayOfYearValidate->{$_} };
578
579     delete $copy{default};
580     $copy{optional} = 1 unless $_ eq 'year' || $_ eq 'month';
581
582     $FromDayOfYearValidate->{$_} = \%copy;
583 }
584 $FromDayOfYearValidate->{day_of_year} =
585     { type => SCALAR,
586       callbacks =>
587       { 'is between 1 and 366' =>
588         sub { $_[0] >= 1 && $_[0] <= 366 }
589       }
590     };
591 sub from_day_of_year
592 {
593     my $class = shift;
594     my %p = validate( @_, $FromDayOfYearValidate );
595
596     my $is_leap_year = $class->_is_leap_year( $p{year} );
597
598     Carp::croak( "$p{year} is not a leap year.\n" )
599         if $p{day_of_year} == 366 && ! $is_leap_year;
600
601     my $month = 1;
602     my $day = delete $p{day_of_year};
603
604     while ( $month <= 12 && $day > $class->_month_length( $p{year}, $month ) )
605     {
606         $day -= $class->_month_length( $p{year}, $month );
607         $month++;
608     }
609
610     return DateTime->new( %p,
611                           month => $month,
612                           day   => $day,
613                         );
614 }
615
616 sub formatter { $_[0]->{formatter} }
617
618 sub clone { bless { %{ $_[0] } }, ref $_[0] }
619
620 sub year {
621     Carp::carp('year() is a read-only accessor') if @_ > 1;
622     return $_[0]->{local_c}{year};
623 }
624
625 sub ce_year { $_[0]->{local_c}{year} <= 0 ?
626               $_[0]->{local_c}{year} - 1 :
627               $_[0]->{local_c}{year} }
628
629 sub era_name { $_[0]->{locale}->era_wide->[ $_[0]->_era_index() ] }
630
631 sub era_abbr { $_[0]->{locale}->era_abbreviated->[ $_[0]->_era_index() ] }
632 # deprecated
633 *era = \&era_abbr;
634
635 sub _era_index { $_[0]->{local_c}{year} <= 0 ? 0 : 1 }
636
637 sub christian_era { $_[0]->ce_year > 0 ? 'AD' : 'BC' }
638 sub secular_era   { $_[0]->ce_year > 0 ? 'CE' : 'BCE' }
639
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 }
643
644 sub month   {
645     Carp::carp('month() is a read-only accessor') if @_ > 1;
646     return $_[0]->{local_c}{month};
647 }
648 *mon = \&month;
649
650 sub month_0 { $_[0]->{local_c}{month} - 1 }
651 *mon_0 = \&month_0;
652
653 sub month_name { $_[0]->{locale}->month_format_wide->[ $_[0]->month_0() ] }
654
655 sub month_abbr { $_[0]->{locale}->month_format_abbreviated->[ $_[0]->month_0() ] }
656
657 sub day_of_month {
658     Carp::carp('day_of_month() is a read-only accessor') if @_ > 1;
659     $_[0]->{local_c}{day};
660 }
661 *day  = \&day_of_month;
662 *mday = \&day_of_month;
663
664 sub weekday_of_month { use integer; ( ( $_[0]->day - 1 ) / 7 ) + 1 }
665
666 sub quarter { $_[0]->{local_c}{quarter} }
667
668 sub quarter_name { $_[0]->{locale}->quarter_format_wide->[ $_[0]->quarter_0() ] }
669 sub quarter_abbr { $_[0]->{locale}->quarter_format_abbreviated->[ $_[0]->quarter_0() ] }
670
671 sub quarter_0 { $_[0]->{local_c}{quarter} - 1 }
672
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;
676
677 sub day_of_week { $_[0]->{local_c}{day_of_week} }
678 *wday = \&day_of_week;
679 *dow  = \&day_of_week;
680
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;
684
685 sub local_day_of_week
686 {
687     my $self = shift;
688
689     my $day = $self->day_of_week();
690
691     my $local_first_day = $self->{locale}->first_day_of_week();
692
693     my $d = ( ( 8 - $local_first_day ) + $day ) % 7;
694
695     return $d == 0 ? 7 : $d;
696 }
697
698 sub day_name { $_[0]->{locale}->day_format_wide->[ $_[0]->day_of_week_0() ] }
699
700 sub day_abbr { $_[0]->{locale}->day_format_abbreviated->[ $_[0]->day_of_week_0() ] }
701
702 sub day_of_quarter { $_[0]->{local_c}{day_of_quarter} }
703 *doq = \&day_of_quarter;
704
705 sub day_of_quarter_0 { $_[0]->day_of_quarter - 1 }
706 *doq_0 = \&day_of_quarter_0;
707
708 sub day_of_year { $_[0]->{local_c}{day_of_year} }
709 *doy = \&day_of_year;
710
711 sub day_of_year_0 { $_[0]->{local_c}{day_of_year} - 1 }
712 *doy_0 = \&day_of_year_0;
713
714 sub am_or_pm { $_[0]->{locale}->am_pm_abbreviated->[ $_[0]->hour() < 12 ? 0 : 1 ] }
715
716 sub ymd
717 {
718     my ( $self, $sep ) = @_;
719     $sep = '-' unless defined $sep;
720
721     return sprintf( "%0.4d%s%0.2d%s%0.2d",
722                     $self->year, $sep,
723                     $self->{local_c}{month}, $sep,
724                     $self->{local_c}{day} );
725 }
726 *date = \&ymd;
727
728 sub mdy
729 {
730     my ( $self, $sep ) = @_;
731     $sep = '-' unless defined $sep;
732
733     return sprintf( "%0.2d%s%0.2d%s%0.4d",
734                     $self->{local_c}{month}, $sep,
735                     $self->{local_c}{day}, $sep,
736                     $self->year );
737 }
738
739 sub dmy
740 {
741     my ( $self, $sep ) = @_;
742     $sep = '-' unless defined $sep;
743
744     return sprintf( "%0.2d%s%0.2d%s%0.4d",
745                     $self->{local_c}{day}, $sep,
746                     $self->{local_c}{month}, $sep,
747                     $self->year );
748 }
749
750 sub hour   {
751     Carp::carp('hour() is a read-only accessor') if @_ > 1;
752     return $_[0]->{local_c}{hour};
753 }
754 sub hour_1 { $_[0]->{local_c}{hour} == 0 ? 24 : $_[0]->{local_c}{hour} }
755
756 sub hour_12   { my $h = $_[0]->hour % 12; return $h ? $h : 12 }
757 sub hour_12_0 { $_[0]->hour % 12 }
758
759 sub minute {
760     Carp::carp('minute() is a read-only accessor') if @_ > 1;
761     return $_[0]->{local_c}{minute};
762 }
763 *min = \&minute;
764
765 sub second {
766     Carp::carp('second() is a read-only accessor') if @_ > 1;
767     return $_[0]->{local_c}{second};
768 }
769 *sec = \&second;
770
771 sub fractional_second { $_[0]->second + $_[0]->nanosecond / MAX_NANOSECONDS }
772
773 sub nanosecond {
774     Carp::carp('nanosecond() is a read-only accessor') if @_ > 1;
775     return $_[0]->{rd_nanosecs};
776 }
777
778 sub millisecond { _round( $_[0]->{rd_nanosecs} / 1000000 ) }
779
780 sub microsecond { _round( $_[0]->{rd_nanosecs} / 1000 ) }
781
782 sub _round
783 {
784     my $val = shift;
785     my $int = int $val;
786
787     return $val - $int >= 0.5 ? $int + 1 : $int;
788 }
789
790 sub leap_seconds
791 {
792     my $self = shift;
793
794     return 0 if $self->{tz}->is_floating;
795
796     return DateTime->_accumulated_leap_seconds( $self->{utc_rd_days} );
797 }
798
799 sub _stringify
800 {
801     my $self = shift;
802
803     return $self->iso8601 unless $self->{formatter};
804     return $self->{formatter}->format_datetime($self);
805 }
806
807 sub hms
808 {
809     my ( $self, $sep ) = @_;
810     $sep = ':' unless defined $sep;
811
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} );
816 }
817 # don't want to override CORE::time()
818 *DateTime::time = \&hms;
819
820 sub iso8601 { join 'T', $_[0]->ymd('-'), $_[0]->hms(':') }
821 *datetime = \&iso8601;
822
823 sub is_leap_year { $_[0]->_is_leap_year( $_[0]->year ) }
824
825 sub week
826 {
827     my $self = shift;
828
829     unless ( defined $self->{local_c}{week_year} )
830     {
831         # This algorithm was taken from Date::Calc's DateCalc.c file
832         my $jan_one_dow_m1 =
833             ( ( $self->_ymd2rd( $self->year, 1, 1 ) + 6 ) % 7 );
834
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;
838
839         if ( $self->{local_c}{week_number} == 0 )
840         {
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} );
844         }
845         elsif ( $self->{local_c}{week_number} == 53 &&
846                 $self->_weeks_in_year( $self->year ) == 52 )
847         {
848             $self->{local_c}{week_number} = 1;
849             $self->{local_c}{week_year} = $self->year + 1;
850         }
851         else
852         {
853             $self->{local_c}{week_year} = $self->year;
854         }
855     }
856
857     return @{ $self->{local_c} }{ 'week_year', 'week_number' }
858 }
859
860 # Also from DateCalc.c
861 sub _weeks_in_year
862 {
863     my $self = shift;
864     my $year = shift;
865
866     my $jan_one_dow =
867         ( ( $self->_ymd2rd( $year, 1, 1 ) + 6 ) % 7 ) + 1;
868     my $dec_31_dow =
869         ( ( $self->_ymd2rd( $year, 12, 31 ) + 6 ) % 7 ) + 1;
870
871     return $jan_one_dow == 4 || $dec_31_dow == 4 ? 53 : 52;
872 }
873
874 sub week_year   { ($_[0]->week)[0] }
875 sub week_number { ($_[0]->week)[1] }
876
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.
880 #
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!
883 sub week_of_month
884 {
885     my $self = shift;
886
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;
890
891     my $wom = int( ( $self->day + $first_wday_of_month - 2 ) / 7 );
892     return ( $first_wday_of_month <= 4 ) ? $wom + 1 : $wom;
893 }
894
895 sub time_zone {
896     Carp::carp('time_zone() is a read-only accessor') if @_ > 1;
897     return $_[0]->{tz};
898 }
899
900 sub offset                     { $_[0]->{tz}->offset_for_datetime( $_[0] ) }
901 sub _offset_for_local_datetime { $_[0]->{tz}->offset_for_local_datetime( $_[0] ) }
902
903 sub is_dst { $_[0]->{tz}->is_dst_for_datetime( $_[0] ) }
904
905 sub time_zone_long_name  { $_[0]->{tz}->name }
906 sub time_zone_short_name { $_[0]->{tz}->short_name_for_datetime( $_[0] ) }
907
908 sub locale {
909     Carp::carp('locale() is a read-only accessor') if @_ > 1;
910     return $_[0]->{locale};
911 }
912 *language = \&locale;
913
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' } }
916
917 # NOTE: no nanoseconds, no leap seconds
918 sub utc_rd_as_seconds   { ( $_[0]->{utc_rd_days} * SECONDS_PER_DAY ) + $_[0]->{utc_rd_secs} }
919
920 # NOTE: no nanoseconds, no leap seconds
921 sub local_rd_as_seconds { ( $_[0]->{local_rd_days} * SECONDS_PER_DAY ) + $_[0]->{local_rd_secs} }
922
923 # RD 1 is JD 1,721,424.5 - a simple offset
924 sub jd
925 {
926     my $self = shift;
927
928     my $jd = $self->{utc_rd_days} + 1_721_424.5;
929
930     my $day_length = $self->_day_length( $self->{utc_rd_days} );
931
932     return ( $jd +
933              ( $self->{utc_rd_secs} / $day_length )  +
934              ( $self->{rd_nanosecs} / $day_length / MAX_NANOSECONDS )
935            );
936 }
937
938 sub mjd { $_[0]->jd - 2_400_000.5 }
939
940 {
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 ) },
969           't' => sub { "\t" },
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 ) )
977                    },
978           'V' => sub { sprintf( '%02d', $_[0]->week_number ) },
979           'w' => sub { my $dow = $_[0]->day_of_week;
980                        return $dow % 7;
981                    },
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 ) )
985                    },
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] ) },
992           '%' => sub { '%' },
993         );
994
995     $strftime_patterns{h} = $strftime_patterns{b};
996
997     sub strftime
998     {
999         my $self = shift;
1000         # make a copy or caller's scalars get munged
1001         my @patterns = @_;
1002
1003         my @r;
1004         foreach my $p (@patterns)
1005         {
1006             $p =~ s/
1007                     (?:
1008                       %{(\w+)}         # method name like %{day_name}
1009                       |
1010                       %([%a-zA-Z])     # single character specifier like %d
1011                       |
1012                       %(\d+)N          # special case for %N
1013                     )
1014                    /
1015                     ( $1
1016                       ? ( $self->can($1) ? $self->$1() : "\%{$1}" )
1017                       : $2
1018                       ? ( $strftime_patterns{$2} ? $strftime_patterns{$2}->($self) : "\%$2" )
1019                       : $3
1020                       ? $strftime_patterns{N}->($self, $3)
1021                       : ''  # this won't happen
1022                     )
1023                    /sgex;
1024
1025             return $p unless wantarray;
1026
1027             push @r, $p;
1028         }
1029
1030         return @r;
1031     }
1032 }
1033
1034 {
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.
1039     my @patterns =
1040         ( qr/GGGGG/  => sub { $_[0]->{locale}->era_narrow->[ $_[0]->_era_index() ] },
1041           qr/GGGG/   => 'era_name',
1042           qr/G{1,3}/ => 'era_abbr',
1043
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() ) },
1053
1054           qr/QQQQ/  => 'quarter_name',
1055           qr/QQQ/   => 'quarter_abbr',
1056           qr/(QQ?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->quarter() ) },
1057
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() ) },
1061
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() ) },
1066
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() ) },
1071
1072           qr/(ww?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->week_number() ) },
1073           qr/W/     => 'week_of_month',
1074
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() ) },
1077
1078           qr/F/    => 'weekday_of_month',
1079           qr/(g+)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->mjd() ) },
1080
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',
1084
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() ) },
1089
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() ) },
1094
1095           qr/a/ => 'am_or_pm',
1096
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 ) },
1103
1104           qr/(mm?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->minute() ) },
1105
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() );
1112                              $val =~ s/^0\.//;
1113                              $val || 0 },
1114           qr/A+/    => sub { ( $_[0]->{local_rd_secs} * 1000 ) + $_[0]->millisecond() },
1115
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() },
1125     );
1126
1127     sub _zero_padded_number
1128     {
1129         my $self = shift;
1130         my $size = length shift;
1131         my $val  = shift;
1132
1133         return sprintf( "%0${size}d", $val );
1134     }
1135
1136     sub _space_padded_string
1137     {
1138         my $self = shift;
1139         my $size = length shift;
1140         my $val  = shift;
1141
1142         return sprintf( "% ${size}s", $val );
1143     }
1144
1145     sub format_cldr
1146     {
1147         my $self = shift;
1148         # make a copy or caller's scalars get munged
1149         my @patterns = @_;
1150
1151         my @r;
1152         foreach my $p (@patterns)
1153         {
1154             $p =~ s/\G
1155                     (?:
1156                       '((?:[^']|'')*)' # quote escaped bit of text
1157                                        # it needs to end with one
1158                                        # quote not followed by
1159                                        # another
1160                       |
1161                       (([a-zA-Z])\3*)     # could be a pattern
1162                       |
1163                       (.)                 # anything else
1164                     )
1165                    /
1166                     defined $1
1167                     ? $1
1168                     : defined $2
1169                     ? $self->_cldr_pattern($2)
1170                     : defined $4
1171                     ? $4
1172                     : undef # should never get here
1173                    /sgex;
1174
1175             $p =~ s/\'\'/\'/g;
1176
1177             return $p unless wantarray;
1178
1179             push @r, $p;
1180         }
1181
1182         return @r;
1183     }
1184
1185     sub _cldr_pattern
1186     {
1187         my $self    = shift;
1188         my $pattern = shift;
1189
1190         for ( my $i = 0; $i < @patterns; $i +=2 )
1191         {
1192             if ( $pattern =~ /$patterns[$i]/ )
1193             {
1194                 my $sub = $patterns[ $i + 1 ];
1195
1196                 return $self->$sub();
1197             }
1198         }
1199
1200         return $pattern;
1201     }
1202 }
1203
1204 sub _format_nanosecs
1205 {
1206     my $self = shift;
1207     my $precision = shift;
1208
1209     my $ret = sprintf( "%09d", $self->{rd_nanosecs} );
1210     return $ret unless $precision;   # default = 9 digits
1211
1212     # rd_nanosecs might contain a fractional separator
1213     my ( $int, $frac ) = split /[.,]/, $self->{rd_nanosecs};
1214     $ret .= $frac if $frac;
1215
1216     return substr( $ret, 0, $precision );
1217 }
1218
1219 sub epoch
1220 {
1221     my $self = shift;
1222
1223     return $self->{utc_c}{epoch}
1224         if exists $self->{utc_c}{epoch};
1225
1226     my ( $year, $month, $day ) = $self->_utc_ymd;
1227     my @hms = $self->_utc_hms;
1228
1229     $self->{utc_c}{epoch} =
1230         timegm_nocheck( ( reverse @hms ),
1231                         $day,
1232                         $month - 1,
1233                         $year,
1234                       );
1235
1236     return $self->{utc_c}{epoch};
1237 }
1238
1239 sub hires_epoch
1240 {
1241     my $self = shift;
1242
1243     my $epoch = $self->epoch;
1244
1245     return undef unless defined $epoch;
1246
1247     my $nano = $self->{rd_nanosecs} / MAX_NANOSECONDS;
1248
1249     return $epoch + $nano;
1250 }
1251
1252 sub is_finite { 1 }
1253 sub is_infinite { 0 }
1254
1255 # added for benefit of DateTime::TimeZone
1256 sub utc_year { $_[0]->{utc_year} }
1257
1258 # returns a result that is relative to the first datetime
1259 sub subtract_datetime
1260 {
1261     my $dt1 = shift;
1262     my $dt2 = shift;
1263
1264     $dt2 = $dt2->clone->set_time_zone( $dt1->time_zone )
1265         unless $dt1->time_zone eq $dt2->time_zone;
1266
1267     # We only want a negative duration if $dt2 > $dt1 ($self)
1268     my ( $bigger, $smaller, $negative ) =
1269         ( $dt1 >= $dt2 ?
1270           ( $dt1, $dt2, 0 ) :
1271           ( $dt2, $dt1, 1 )
1272         );
1273
1274     my $is_floating = $dt1->time_zone->is_floating &&
1275                       $dt2->time_zone->is_floating;
1276
1277
1278     my $minute_length = 60;
1279     unless ($is_floating)
1280     {
1281         my ( $utc_rd_days, $utc_rd_secs ) = $smaller->utc_rd_values;
1282
1283         if ( $utc_rd_secs >= 86340 && ! $is_floating )
1284         {
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.
1292
1293             $minute_length = $dt1->_day_length($utc_rd_days) - 86340;
1294         }
1295     }
1296
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
1301     # local time.
1302     #
1303     # This produces the most "intuitive" results, though there are
1304     # still reversibility problems with the resultant duration.
1305     #
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
1312        )
1313     {
1314
1315         $bigger_min -= 60
1316             # it's a 23 hour (local) day
1317             if ( $bigger->is_dst
1318                  &&
1319                  do { local $@;
1320                       my $prev_day = eval { $bigger->clone->subtract( days => 1 ) };
1321                       $prev_day && ! $prev_day->is_dst ? 1 : 0 }
1322                );
1323
1324         $bigger_min += 60
1325             # it's a 25 hour (local) day
1326             if ( ! $bigger->is_dst
1327                  &&
1328                  do { local $@;
1329                       my $prev_day = eval { $bigger->clone->subtract( days => 1 ) };
1330                       $prev_day && $prev_day->is_dst ? 1 : 0 }
1331                );
1332     }
1333
1334     my ( $months, $days, $minutes, $seconds, $nanoseconds ) =
1335         $dt1->_adjust_for_positive_difference
1336             ( $bigger->year * 12 + $bigger->month, $smaller->year * 12 + $smaller->month,
1337
1338               $bigger->day, $smaller->day,
1339
1340               $bigger_min, $smaller->hour * 60 + $smaller->minute,
1341
1342               $bigger->second, $smaller->second,
1343
1344               $bigger->nanosecond, $smaller->nanosecond,
1345
1346               $minute_length,
1347
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 ),
1352             );
1353
1354     if ($negative)
1355     {
1356         for ( $months, $days, $minutes, $seconds, $nanoseconds )
1357         {
1358             # Some versions of Perl can end up with -0 if we do "0 * -1"!!
1359             $_ *= -1 if $_;
1360         }
1361     }
1362
1363     return
1364         $dt1->duration_class->new
1365             ( months      => $months,
1366               days        => $days,
1367               minutes     => $minutes,
1368               seconds     => $seconds,
1369               nanoseconds => $nanoseconds,
1370             );
1371 }
1372
1373 sub _adjust_for_positive_difference
1374 {
1375     my ( $self,
1376          $month1, $month2,
1377          $day1, $day2,
1378          $min1, $min2,
1379          $sec1, $sec2,
1380          $nano1, $nano2,
1381          $minute_length,
1382          $month_length,
1383        ) = @_;
1384
1385     if ( $nano1 < $nano2 )
1386     {
1387         $sec1--;
1388         $nano1 += MAX_NANOSECONDS;
1389     }
1390
1391     if ( $sec1 < $sec2 )
1392     {
1393         $min1--;
1394         $sec1 += $minute_length;
1395     }
1396
1397     # A day always has 24 * 60 minutes, though the minutes may vary in
1398     # length.
1399     if ( $min1 < $min2 )
1400     {
1401         $day1--;
1402         $min1 += 24 * 60;
1403     }
1404
1405     if ( $day1 < $day2 )
1406     {
1407         $month1--;
1408         $day1 += $month_length;
1409     }
1410
1411     return ( $month1 - $month2,
1412              $day1 - $day2,
1413              $min1 - $min2,
1414              $sec1 - $sec2,
1415              $nano1 - $nano2,
1416            );
1417 }
1418
1419 sub subtract_datetime_absolute
1420 {
1421     my $self = shift;
1422     my $dt = shift;
1423
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;
1427
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;
1431
1432     my $seconds = $utc_rd_secs1 - $utc_rd_secs2;
1433     my $nanoseconds = $self->nanosecond - $dt->nanosecond;
1434
1435     if ( $nanoseconds < 0 )
1436     {
1437         $seconds--;
1438         $nanoseconds += MAX_NANOSECONDS;
1439     }
1440
1441     return
1442         $self->duration_class->new
1443             ( seconds     => $seconds,
1444               nanoseconds => $nanoseconds,
1445             );
1446 }
1447
1448 sub delta_md
1449 {
1450     my $self = shift;
1451     my $dt = shift;
1452
1453     my ( $smaller, $bigger ) = sort $self, $dt;
1454
1455     my ( $months, $days, undef, undef, undef ) =
1456         $dt->_adjust_for_positive_difference
1457             ( $bigger->year * 12 + $bigger->month, $smaller->year * 12 + $smaller->month,
1458
1459               $bigger->day, $smaller->day,
1460
1461               0, 0,
1462
1463               0, 0,
1464
1465               0, 0,
1466
1467               60,
1468
1469               $smaller->_month_length( $smaller->year, $smaller->month ),
1470             );
1471
1472     return $self->duration_class->new( months => $months,
1473                                        days   => $days );
1474 }
1475
1476 sub delta_days
1477 {
1478     my $self = shift;
1479     my $dt = shift;
1480
1481     my $days = abs( ($self->local_rd_values)[0] - ($dt->local_rd_values)[0] );
1482
1483     $self->duration_class->new( days => $days );
1484 }
1485
1486 sub delta_ms
1487 {
1488     my $self = shift;
1489     my $dt = shift;
1490
1491     my ( $smaller, $greater ) = sort $self, $dt;
1492
1493     my $days = int( $greater->jd - $smaller->jd );
1494
1495     my $dur = $greater->subtract_datetime($smaller);
1496
1497     my %p;
1498     $p{hours}   = $dur->hours + ( $days * 24 );
1499     $p{minutes} = $dur->minutes;
1500     $p{seconds} = $dur->seconds;
1501
1502     return $self->duration_class->new(%p);
1503 }
1504
1505 sub _add_overload
1506 {
1507     my ( $dt, $dur, $reversed ) = @_;
1508
1509     if ($reversed)
1510     {
1511         ( $dur, $dt ) = ( $dt, $dur );
1512     }
1513
1514     unless ( DateTime::Helpers::isa( $dur, 'DateTime::Duration' ) )
1515     {
1516         my $class = ref $dt;
1517         my $dt_string = overload::StrVal($dt);
1518
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." );
1522     }
1523
1524     return $dt->clone->add_duration($dur);
1525 }
1526
1527 sub _subtract_overload
1528 {
1529     my ( $date1, $date2, $reversed ) = @_;
1530
1531     if ($reversed)
1532     {
1533         ( $date2, $date1 ) = ( $date1, $date2 );
1534     }
1535
1536     if ( DateTime::Helpers::isa( $date2, 'DateTime::Duration' ) )
1537     {
1538         my $new = $date1->clone;
1539         $new->add_duration( $date2->inverse );
1540         return $new;
1541     }
1542     elsif ( DateTime::Helpers::isa( $date2, 'DateTime' ) )
1543     {
1544         return $date1->subtract_datetime($date2);
1545     }
1546     else
1547     {
1548         my $class = ref $date1;
1549         my $dt_string = overload::StrVal($date1);
1550
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." );
1554     }
1555 }
1556
1557 sub add
1558 {
1559     my $self = shift;
1560
1561     return $self->add_duration( $self->duration_class->new(@_) );
1562 }
1563
1564 sub subtract
1565 {
1566     my $self = shift;
1567
1568     return $self->subtract_duration( $self->duration_class->new(@_) );
1569 }
1570
1571 sub subtract_duration { return $_[0]->add_duration( $_[1]->inverse ) }
1572
1573 {
1574     my @spec = ( { isa => 'DateTime::Duration' } );
1575     sub add_duration
1576     {
1577         my $self = shift;
1578         my ($dur) = validate_pos( @_, @spec );
1579
1580         # simple optimization
1581         return $self if $dur->is_zero;
1582
1583         my %deltas = $dur->deltas;
1584
1585         # This bit isn't quite right since DateTime::Infinite::Future -
1586         # infinite duration should NaN
1587         foreach my $val ( values %deltas )
1588         {
1589             my $inf;
1590             if ( $val == INFINITY )
1591             {
1592                 $inf = DateTime::Infinite::Future->new;
1593             }
1594             elsif ( $val == NEG_INFINITY )
1595             {
1596                 $inf = DateTime::Infinite::Past->new;
1597             }
1598
1599             if ($inf)
1600             {
1601                 %$self = %$inf;
1602                 bless $self, ref $inf;
1603
1604                 return $self;
1605             }
1606         }
1607
1608         return $self if $self->is_infinite;
1609
1610         if ( $deltas{days} )
1611         {
1612             $self->{local_rd_days} += $deltas{days};
1613
1614             $self->{utc_year} += int( $deltas{days} / 365 ) + 1;
1615         }
1616
1617         if ( $deltas{months} )
1618         {
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} )
1625                               );
1626
1627             $d -= 1 if $dur->is_preserve_mode;
1628
1629             if ( ! $dur->is_wrap_mode && $d > 28 )
1630             {
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 );
1633
1634                 # what day of the month is it? (discard year and month)
1635                 my $last_day = ($self->_rd2ymd( $self->{local_rd_days} ))[2];
1636
1637                 # if our original day was less than the last day,
1638                 # use that instead
1639                 $self->{local_rd_days} -= $last_day - $d if $last_day > $d;
1640             }
1641             else
1642             {
1643                 $self->{local_rd_days} = $self->_ymd2rd( $y, $m + $deltas{months}, $d );
1644             }
1645
1646             $self->{utc_year} += int( $deltas{months} / 12 ) + 1;
1647         }
1648
1649         if ( $deltas{days} || $deltas{months} )
1650         {
1651             $self->_calc_utc_rd;
1652
1653             $self->_handle_offset_modifier( $self->second );
1654         }
1655
1656         if ( $deltas{minutes} )
1657         {
1658             $self->{utc_rd_secs} += $deltas{minutes} * 60;
1659
1660             # This intentionally ignores leap seconds
1661             $self->_normalize_tai_seconds( $self->{utc_rd_days}, $self->{utc_rd_secs} );
1662         }
1663
1664         if ( $deltas{seconds} || $deltas{nanoseconds} )
1665         {
1666             $self->{utc_rd_secs} += $deltas{seconds};
1667
1668             if ( $deltas{nanoseconds} )
1669             {
1670                 $self->{rd_nanosecs} += $deltas{nanoseconds};
1671                 $self->_normalize_nanoseconds( $self->{utc_rd_secs}, $self->{rd_nanosecs} );
1672             }
1673
1674             $self->_normalize_seconds;
1675
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
1678             # that)
1679             $self->_handle_offset_modifier( $self->second + $deltas{seconds} );
1680         }
1681
1682         my $new =
1683             (ref $self)->from_object
1684                 ( object => $self,
1685                   locale => $self->{locale},
1686                   ( $self->{formatter} ? ( formatter => $self->{formatter} ) : () ),
1687                  );
1688
1689         %$self = %$new;
1690
1691         return $self;
1692     }
1693 }
1694
1695 sub _compare_overload
1696 {
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] );
1700 }
1701
1702 sub compare
1703 {
1704     shift->_compare( @_, 0 );
1705 }
1706
1707 sub compare_ignore_floating
1708 {
1709     shift->_compare( @_, 1 );
1710 }
1711
1712 sub _compare
1713 {
1714     my ( $class, $dt1, $dt2, $consistent ) = ref $_[0] ? ( undef, @_ ) : @_;
1715
1716     return undef unless defined $dt2;
1717
1718     if ( ! ref $dt2 && ( $dt2 == INFINITY || $dt2 == NEG_INFINITY ) )
1719     {
1720         return $dt1->{utc_rd_days} <=> $dt2;
1721     }
1722
1723     unless ( DateTime::Helpers::can( $dt1, 'utc_rd_values' )
1724              && DateTime::Helpers::can( $dt2, 'utc_rd_values' ) )
1725     {
1726         my $dt1_string = overload::StrVal($dt1);
1727         my $dt2_string = overload::StrVal($dt2);
1728
1729         Carp::croak( "A DateTime object can only be compared to"
1730                      . " another DateTime object ($dt1_string, $dt2_string)." );
1731     }
1732
1733     if ( ! $consistent &&
1734          DateTime::Helpers::can( $dt1, 'time_zone' ) &&
1735          DateTime::Helpers::can( $dt2, 'time_zone' )
1736        )
1737     {
1738         my $is_floating1 = $dt1->time_zone->is_floating;
1739         my $is_floating2 = $dt2->time_zone->is_floating;
1740
1741         if ( $is_floating1 && ! $is_floating2 )
1742         {
1743             $dt1 = $dt1->clone->set_time_zone( $dt2->time_zone );
1744         }
1745         elsif ( $is_floating2 && ! $is_floating1 )
1746         {
1747             $dt2 = $dt2->clone->set_time_zone( $dt1->time_zone );
1748         }
1749     }
1750
1751     my @dt1_components = $dt1->utc_rd_values;
1752     my @dt2_components = $dt2->utc_rd_values;
1753
1754     foreach my $i ( 0..2 )
1755     {
1756         return $dt1_components[$i] <=> $dt2_components[$i]
1757             if $dt1_components[$i] != $dt2_components[$i]
1758     }
1759
1760     return 0;
1761 }
1762
1763 sub _string_equals_overload
1764 {
1765     my ( $class, $dt1, $dt2 ) = ref $_[0] ? ( undef, @_ ) : @_;
1766
1767     return unless
1768         (    DateTime::Helpers::can( $dt1, 'utc_rd_values' )
1769           && DateTime::Helpers::can( $dt2, 'utc_rd_values' )
1770         );
1771
1772     $class ||= ref $dt1;
1773     return ! $class->compare( $dt1, $dt2 );
1774 }
1775
1776 sub _string_not_equals_overload
1777 {
1778     return ! _string_equals_overload(@_);
1779 }
1780
1781 sub _normalize_nanoseconds
1782 {
1783     use integer;
1784
1785     # seconds, nanoseconds
1786     if ( $_[2] < 0 )
1787     {
1788         my $overflow = 1 + $_[2] / MAX_NANOSECONDS;
1789         $_[2] += $overflow * MAX_NANOSECONDS;
1790         $_[1] -= $overflow;
1791     }
1792     elsif ( $_[2] >= MAX_NANOSECONDS )
1793     {
1794         my $overflow = $_[2] / MAX_NANOSECONDS;
1795         $_[2] -= $overflow * MAX_NANOSECONDS;
1796         $_[1] += $overflow;
1797     }
1798 }
1799
1800 # Many of the same parameters as new() but all of them are optional,
1801 # and there are no defaults.
1802 my $SetValidate =
1803     { map { my %copy = %{ $BasicValidate->{$_} };
1804             delete $copy{default};
1805             $copy{optional} = 1;
1806             $_ => \%copy }
1807       keys %$BasicValidate };
1808
1809 sub set
1810 {
1811     my $self = shift;
1812     my %p = validate( @_, $SetValidate );
1813
1814     my $new_dt = $self->_new_from_self(%p);
1815
1816     %$self = %$new_dt;
1817
1818     return $self;
1819 }
1820
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] ) }
1828
1829 sub set_locale { $_[0]->set( locale => $_[1] ) }
1830
1831 sub set_formatter { $_[0]->{formatter} = $_[1] }
1832
1833 {
1834     my %TruncateDefault = ( month  => 1,
1835                             day    => 1,
1836                             hour   => 0,
1837                             minute => 0,
1838                             second => 0,
1839                             nanosecond => 0,
1840                           );
1841     my $re = join '|', 'year', 'week', grep { $_ ne 'nanosecond' } keys %TruncateDefault;
1842     my $spec = { to => { regex => qr/^(?:$re)/ } };
1843
1844     sub truncate
1845     {
1846         my $self = shift;
1847         my %p = validate( @_, $spec );
1848
1849         my %new;
1850         if ( $p{to} eq 'week' )
1851         {
1852             my $day_diff = $self->day_of_week - 1;
1853
1854             if ($day_diff)
1855             {
1856                 $self->add( days => -1 * $day_diff );
1857             }
1858
1859             return $self->truncate( to => 'day' );
1860         }
1861         else
1862         {
1863             my $truncate;
1864             foreach my $f ( qw( year month day hour minute second nanosecond ) )
1865             {
1866                 $new{$f} = $truncate ? $TruncateDefault{$f} : $self->$f();
1867
1868                 $truncate = 1 if $p{to} eq $f;
1869             }
1870         }
1871
1872         my $new_dt = $self->_new_from_self(%new);
1873
1874         %$self = %$new_dt;
1875
1876         return $self;
1877     }
1878 }
1879
1880 sub set_time_zone
1881 {
1882     my ( $self, $tz ) = @_;
1883
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
1886     # bit of speed.
1887     return $self if $self->{tz} eq $tz;
1888
1889     my $was_floating = $self->{tz}->is_floating;
1890
1891     $self->{tz} = ref $tz ? $tz : DateTime::TimeZone->new( name => $tz );
1892
1893     $self->_handle_offset_modifier( $self->second, 1 );
1894
1895     # if it either was or now is floating (but not both)
1896     if ( $self->{tz}->is_floating xor $was_floating )
1897     {
1898         $self->_calc_utc_rd;
1899     }
1900     elsif ( ! $was_floating )
1901     {
1902         $self->_calc_local_rd;
1903     }
1904
1905     return $self;
1906 }
1907
1908 sub STORABLE_freeze
1909 {
1910     my $self = shift;
1911     my $cloning = shift;
1912
1913     my $serialized = '';
1914     foreach my $key ( qw( utc_rd_days
1915                           utc_rd_secs
1916                           rd_nanosecs ) )
1917     {
1918         $serialized .= "$key:$self->{$key}|";
1919     }
1920
1921     # not used yet, but may be handy in the future.
1922     $serialized .= "version:$VERSION";
1923
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};
1928 }
1929
1930 sub STORABLE_thaw
1931 {
1932     my $self = shift;
1933     my $cloning = shift;
1934     my $serialized = shift;
1935
1936     my %serialized = map { split /:/ } split /\|/, $serialized;
1937
1938     my ( $locale, $tz, $formatter );
1939
1940     # more recent code version
1941     if (@_)
1942     {
1943         ( $locale, $tz, $formatter ) = @_;
1944     }
1945     else
1946     {
1947         $tz = DateTime::TimeZone->new( name => delete $serialized{tz} );
1948
1949         $locale =
1950             DateTime::Locale->load( exists $serialized{language}
1951                                     ? delete $serialized{language}
1952                                     : delete $serialized{locale}
1953                                   );
1954     }
1955
1956     delete $serialized{version};
1957
1958     my $object = bless { utc_vals => [ $serialized{utc_rd_days},
1959                                        $serialized{utc_rd_secs},
1960                                        $serialized{rd_nanosecs},
1961                                      ],
1962                          tz       => $tz,
1963                        }, 'DateTime::_Thawed';
1964
1965     my %formatter = defined $$formatter ? ( formatter => $$formatter ) : ();
1966     my $new = (ref $self)->from_object( object => $object,
1967                                         locale => $locale,
1968                                         %formatter,
1969                                       );
1970
1971     %$self = %$new;
1972
1973     return $self;
1974 }
1975
1976
1977 package DateTime::_Thawed;
1978
1979 sub utc_rd_values { @{ $_[0]->{utc_vals} } }
1980
1981 sub time_zone { $_[0]->{tz} }
1982
1983
1984 1;
1985
1986 __END__
1987
1988 =head1 NAME
1989
1990 DateTime - A date and time object
1991
1992 =head1 SYNOPSIS
1993
1994   use DateTime;
1995
1996   $dt = DateTime->new( year   => 1964,
1997                        month  => 10,
1998                        day    => 16,
1999                        hour   => 16,
2000                        minute => 12,
2001                        second => 47,
2002                        nanosecond => 500000000,
2003                        time_zone => 'Asia/Taipei',
2004                      );
2005
2006   $dt = DateTime->from_epoch( epoch => $epoch );
2007   $dt = DateTime->now; # same as ( epoch => time() )
2008
2009   $year   = $dt->year;
2010   $month  = $dt->month;          # 1-12 - also mon
2011
2012   $day    = $dt->day;            # 1-31 - also day_of_month, mday
2013
2014   $dow    = $dt->day_of_week;    # 1-7 (Monday is 1) - also dow, wday
2015
2016   $hour   = $dt->hour;           # 0-23
2017   $minute = $dt->minute;         # 0-59 - also min
2018
2019   $second = $dt->second;         # 0-61 (leap seconds!) - also sec
2020
2021   $doy    = $dt->day_of_year;    # 1-366 (leap years) - also doy
2022
2023   $doq    = $dt->day_of_quarter; # 1.. - also doq
2024
2025   $qtr    = $dt->quarter;        # 1-4
2026
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
2029
2030   $ymd    = $dt->ymd;           # 2002-12-06
2031   $ymd    = $dt->ymd('/');      # 2002/12/06 - also date
2032
2033   $mdy    = $dt->mdy;           # 12-06-2002
2034   $mdy    = $dt->mdy('/');      # 12/06/2002
2035
2036   $dmy    = $dt->dmy;           # 06-12-2002
2037   $dmy    = $dt->dmy('/');      # 06/12/2002
2038
2039   $hms    = $dt->hms;           # 14:02:29
2040   $hms    = $dt->hms('!');      # 14!02!29 - also time
2041
2042   $is_leap  = $dt->is_leap_year;
2043
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, ...
2049
2050   # May not work for all possible datetime, see the docs on this
2051   # method for more details.
2052   $epoch_time  = $dt->epoch;
2053
2054   $dt2 = $dt + $duration_object;
2055
2056   $dt3 = $dt - $duration_object;
2057
2058   $duration_object = $dt - $dt2;
2059
2060   $dt->set( year => 1882 );
2061
2062   $dt->set_time_zone( 'America/Chicago' );
2063
2064   $dt->set_formatter( $formatter );
2065
2066 =head1 DESCRIPTION
2067
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>.
2073
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.
2080
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".
2083
2084 For infinite datetimes, please see the
2085 L<DateTime::Infinite|DateTime::Infinite> module.
2086
2087 =head1 USAGE
2088
2089 =head2 0-based Versus 1-based Numbers
2090
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.
2093
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.
2098
2099 The C<day_of_week_0()> method still treats Monday as the first day of
2100 the week.
2101
2102 All I<time>-related numbers such as hour, minute, and second are
2103 0-based.
2104
2105 Years are neither, as they can be both positive or negative, unlike
2106 any other datetime component.  There I<is> a year 0.
2107
2108 There is no C<quarter_0()> method.
2109
2110 =head2 Error Handling
2111
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.
2117
2118 =head2 Locales
2119
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.
2125
2126 =head2 Floating DateTimes
2127
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.
2134
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.
2140
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
2143 datetimes.
2144
2145 =head2 Math
2146
2147 If you are going to be using doing date math, please read the section
2148 L<How Datetime Math is Done>.
2149
2150 =head2 Time Zone Warnings
2151
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:
2157
2158   our $App::LocalTZ = DateTime::TimeZone->new( name => 'local' );
2159
2160   ... # then everywhere else
2161
2162   my $dt = DateTime->new( ..., time_zone => $App::LocalTZ );
2163
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.
2167
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.
2173
2174 =head2 Methods
2175
2176 =head3 Constructors
2177
2178 All constructors can die when invalid parameters are given.
2179
2180 =over 4
2181
2182 =item * DateTime->new( ... )
2183
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.
2187
2188   my $dt = DateTime->new( year   => 1066,
2189                           month  => 10,
2190                           day    => 25,
2191                           hour   => 7,
2192                           minute => 15,
2193                           second => 47,
2194                           nanosecond => 500000000,
2195                           time_zone  => 'America/Chicago',
2196                         );
2197
2198 DateTime validates the "month", "day", "hour", "minute", and "second",
2199 and "nanosecond" parameters.  The valid values for these parameters are:
2200
2201 =over 8
2202
2203 =item * month
2204
2205 1-12
2206
2207 =item * day
2208
2209 1-31, and it must be within the valid range of days for the specified
2210 month
2211
2212 =item * hour
2213
2214 0-23
2215
2216 =item * minute
2217
2218 0-59
2219
2220 =item * second
2221
2222 0-61 (to allow for leap seconds).  Values of 60 or 61 are only allowed
2223 when they match actual leap seconds.
2224
2225 =item * nanosecond
2226
2227 >= 0
2228
2229 =back
2230
2231 =back
2232
2233 Invalid parameter types (like an array reference) will cause the
2234 constructor to die.
2235
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.
2239
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.
2243
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.
2247
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.
2254
2255 The default time zone is "floating".
2256
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.
2260
2261 =head4 Parsing Dates
2262
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".
2265
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.
2269
2270 =head4 Ambiguous Local Times
2271
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.
2279
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,
2283 for example:
2284
2285   # This object represent 01:30:00 standard time
2286   my $dt = DateTime->new( year   => 2003,
2287                           month  => 10,
2288                           day    => 26,
2289                           hour   => 1,
2290                           minute => 30,
2291                           second => 0,
2292                           time_zone => 'America/Chicago',
2293                         );
2294
2295   print $dt->hms;  # prints 01:30:00
2296
2297   # Now the object represent 01:30:00 saving time
2298   $dt->subtract( hours => 1 );
2299
2300   print $dt->hms;  # still prints 01:30:00
2301
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.
2305
2306 =head4 Invalid Local Times
2307
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!
2314
2315 Attempting to create an invalid time currently causes a fatal error.
2316 This may change in future version of this module.
2317
2318 =over 4
2319
2320 =item * DateTime->from_epoch( epoch => $epoch, ... )
2321
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.
2325
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.
2331
2332 By default, the returned object will be in the UTC time zone.
2333
2334 =item * DateTime->now( ... )
2335
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.
2339
2340 By default, the returned object will be in the UTC time zone.
2341
2342 =item * DateTime->today( ... )
2343
2344 This class method is equivalent to:
2345
2346   DateTime->now->truncate( to => 'day' );
2347
2348 =item * DateTime->from_object( object => $object, ... )
2349
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
2355
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>
2358 object.
2359
2360 Otherwise, the returned object will be in the floating time zone.
2361
2362 =item * DateTime->last_day_of_month( ... )
2363
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.
2367
2368 =item * DateTime->from_day_of_year( ... )
2369
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
2374 leap years.
2375
2376 =item * $dt->clone()
2377
2378 This object method returns a new object that is replica of the object
2379 upon which the method is called.
2380
2381 =back
2382
2383 =head3 "Get" Methods
2384
2385 This class has many methods for retrieving information about an
2386 object.
2387
2388 =over 4
2389
2390 =item * $dt->year()
2391
2392 Returns the year.
2393
2394 =item * $dt->ce_year()
2395
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".
2398
2399 =item * $dt->era_name()
2400
2401 Returns the long name of the current era, something like "Before
2402 Christ".  See the L<Locales|/Locales> section for more details.
2403
2404 =item * $dt->era_abbr()
2405
2406 Returns the abbreviated name of the current era, something like "BC".
2407 See the L<Locales|/Locales> section for more details.
2408
2409 =item * $dt->christian_era()
2410
2411 Returns a string, either "BC" or "AD", according to the year.
2412
2413 =item * $dt->secular_era()
2414
2415 Returns a string, either "BCE" or "CE", according to the year.
2416
2417 =item * $dt->year_with_era()
2418
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".
2422
2423 =item * $dt->year_with_christian_era()
2424
2425 Like C<year_with_era()>, but uses the christian_era() to get the era
2426 name.
2427
2428 =item * $dt->year_with_secular_era()
2429
2430 Like C<year_with_era()>, but uses the secular_era() method to get the
2431 era name.
2432
2433 =item * $dt->month()
2434
2435 =item * $dt->mon()
2436
2437 Returns the month of the year, from 1..12.
2438
2439 =item * $dt->month_name()
2440
2441 Returns the name of the current month.  See the
2442 L<Locales|/Locales> section for more details.
2443
2444 =item * $dt->month_abbr()
2445
2446 Returns the abbreviated name of the current month.  See the
2447 L<Locales|/Locales> section for more details.
2448
2449 =item * $dt->day_of_month()
2450
2451 =item * $dt->day()
2452
2453 =item * $dt->mday()
2454
2455 Returns the day of the month, from 1..31.
2456
2457 =item * $dt->day_of_week()
2458
2459 =item * $dt->wday()
2460
2461 =item * $dt->dow()
2462
2463 Returns the day of the week as a number, from 1..7, with 1 being
2464 Monday and 7 being Sunday.
2465
2466 =item * $dt->local_day_of_week()
2467
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.
2470
2471 =item * $dt->day_name()
2472
2473 Returns the name of the current day of the week.  See the
2474 L<Locales|/Locales> section for more details.
2475
2476 =item * $dt->day_abbr()
2477
2478 Returns the abbreviated name of the current day of the week.  See the
2479 L<Locales|/Locales> section for more details.
2480
2481 =item * $dt->day_of_year()
2482
2483 =item * $dt->doy()
2484
2485 Returns the day of the year.
2486
2487 =item * $dt->quarter()
2488
2489 Returns the quarter of the year, from 1..4.
2490
2491 =item * $dt->quarter_name()
2492
2493 Returns the name of the current quarter.  See the
2494 L<Locales|/Locales> section for more details.
2495
2496 =item * $dt->quarter_abbr()
2497
2498 Returns the abbreviated name of the current quarter.  See the
2499 L<Locales|/Locales> section for more details.
2500
2501 =item * $dt->day_of_quarter()
2502
2503 =item * $dt->doq()
2504
2505 Returns the day of the quarter.
2506
2507 =item * $dt->weekday_of_month()
2508
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.
2512
2513 =item * $dt->ymd( $optional_separator ) - also $dt->date(...)
2514
2515 =item * $dt->mdy( $optional_separator )
2516
2517 =item * $dt->dmy( $optional_separator )
2518
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.
2522
2523 By default, the values are separated by a dash (-), but this can be
2524 overridden by passing a value to the method.
2525
2526 =item * $dt->hour()
2527
2528 Returns the hour of the day, from 0..23.
2529
2530 =item * $dt->hour_1()
2531
2532 Returns the hour of the day, from 1..24.
2533
2534 =item * $dt->hour_12()
2535
2536 Returns the hour of the day, from 1..12.
2537
2538 =item * $dt->hour_12_0()
2539
2540 Returns the hour of the day, from 0..11.
2541
2542 =item * $dt->am_or_pm()
2543
2544 Returns the appropriate localized abbreviation, depending on the
2545 current hour.
2546
2547 =item * $dt->minute()
2548
2549 =item * $dt->min()
2550
2551 Returns the minute of the hour, from 0..59.
2552
2553 =item * $dt->second()
2554
2555 =item * $dt->sec()
2556
2557 Returns the second, from 0..61.  The values 60 and 61 are used for
2558 leap seconds.
2559
2560 =item * $dt->fractional_second()
2561
2562 Returns the second, as a real number from 0.0 until 61.999999999
2563
2564 The values 60 and 61 are used for leap seconds.
2565
2566 =item * $dt->millisecond()
2567
2568 Returns the fractional part of the second as milliseconds (1E-3 seconds).
2569
2570 Half a second is 500 milliseconds.
2571
2572 =item * $dt->microsecond()
2573
2574 Returns the fractional part of the second as microseconds (1E-6
2575 seconds).  This value will be rounded to an integer.
2576
2577 Half a second is 500_000 microseconds.  This value will be rounded to
2578 an integer.
2579
2580 =item * $dt->nanosecond()
2581
2582 Returns the fractional part of the second as nanoseconds (1E-9 seconds).
2583
2584 Half a second is 500_000_000 nanoseconds.
2585
2586 =item * $dt->hms( $optional_separator )
2587
2588 =item * $dt->time( $optional_separator )
2589
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.
2592
2593 =item * $dt->datetime()
2594
2595 =item * $dt->iso8601()
2596
2597 This method is equivalent to:
2598
2599   $dt->ymd('-') . 'T' . $dt->hms(':')
2600
2601 =item * $dt->is_leap_year()
2602
2603 This method returns a true or false indicating whether or not the
2604 datetime object is in a leap year.
2605
2606 =item * $dt->week()
2607
2608  ($week_year, $week_number) = $dt->week;
2609
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.
2613
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.
2617
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.
2622
2623 =item * $dt->week_year()
2624
2625 Returns the year of the week.
2626
2627 =item * $dt->week_number()
2628
2629 Returns the week of the year, from 1..53.
2630
2631 =item * $dt->week_of_month()
2632
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.
2638
2639 =item * $dt->jd()
2640
2641 =item * $dt->mjd()
2642
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.
2646
2647 =item * $dt->time_zone()
2648
2649 This returns the C<DateTime::TimeZone> object for the datetime object.
2650
2651 =item * $dt->offset()
2652
2653 This returns the offset from UTC, in seconds, of the datetime object
2654 according to the time zone.
2655
2656 =item * $dt->is_dst()
2657
2658 Returns a boolean indicating whether or not the datetime object is
2659 currently in Daylight Saving Time or not.
2660
2661 =item * $dt->time_zone_long_name()
2662
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
2665 specifier.
2666
2667 =item * $dt->time_zone_short_name()
2668
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.
2673
2674 =item * $dt->strftime( $format, ... )
2675
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.
2679
2680 See the L<strftime Patterns> section for a list of all possible
2681 strftime patterns.
2682
2683 If you give a pattern that doesn't exist, then it is simply treated as
2684 text.
2685
2686 =item * $dt->format_cldr( $format, ... )
2687
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.
2691
2692 See the L<CLDR Patterns> section for a list of all possible CLDR
2693 patterns.
2694
2695 If you give a pattern that doesn't exist, then it is simply treated as
2696 text.
2697
2698 =item * $dt->epoch()
2699
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.
2704
2705 The return value from this method is always an integer.
2706
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.
2710
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).
2715
2716 =item * $dt->hires_epoch()
2717
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>
2721 module.
2722
2723 =item * $dt->is_finite()
2724
2725 =item * $dt->is_infinite
2726
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>.
2730
2731 =item * $dt->utc_rd_values()
2732
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.
2736
2737 =item * $dt->local_rd_values()
2738
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>.
2743
2744 =item * $dt->leap_seconds()
2745
2746 Returns the number of leap seconds that have happened up to the
2747 datetime represented by the object.  For floating datetimes, this
2748 always returns 0.
2749
2750 =item * $dt->utc_rd_as_seconds()
2751
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.
2755
2756 =item * $dt->local_rd_as_seconds() - deprecated
2757
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.
2761
2762 =item * $dt->locale()
2763
2764 Returns the current locale object.
2765
2766 =item * $dt->formatter()
2767
2768 Returns current formatter object or class. See L<Formatters And
2769 Stringification> for details.
2770
2771 =back
2772
2773 =head3 "Set" Methods
2774
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:
2778
2779   my $dt = DateTime->now->set_time_zone( 'Australia/Sydney' );
2780
2781   my $first = DateTime
2782                 ->last_day_of_month( year => 2003, month => 3 )
2783                 ->add( days => 1 )
2784                 ->subtract( seconds => 1 );
2785
2786 =over 4
2787
2788 =item * $dt->set( .. )
2789
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.
2794
2795 This method performs parameters validation just as is done in the
2796 C<new()> method.
2797
2798 =item * $dt->set_year()
2799
2800 =item * $dt->set_month()
2801
2802 =item * $dt->set_day()
2803
2804 =item * $dt->set_hour()
2805
2806 =item * $dt->set_minute()
2807
2808 =item * $dt->set_second()
2809
2810 =item * $dt->set_nanosecond()
2811
2812 =item * $dt->set_locale()
2813
2814 These are shortcuts to calling C<set()> with a single key.  They all
2815 take a single parameter.
2816
2817 =item * $dt->truncate( to => ... )
2818
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.
2825
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.
2828
2829 =item * $dt->set_time_zone( $tz )
2830
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.
2835
2836 For example:
2837
2838   my $dt = DateTime->new( year => 2000, month => 5, day => 10,
2839                           hour => 15, minute => 15,
2840                           time_zone => 'America/Los_Angeles', );
2841
2842   print $dt->hour; # prints 15
2843
2844   $dt->set_time_zone( 'America/Chicago' );
2845
2846   print $dt->hour; # prints 17
2847
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.
2852
2853 Fans of Tsai Ming-Liang's films will be happy to know that this does
2854 work:
2855
2856   my $dt = DateTime->now( time_zone => 'Asia/Taipei' );
2857
2858   $dt->set_time_zone( 'Europe/Paris' );
2859
2860 Yes, now we can know "ni3 na4 bian1 ji2dian3?"
2861
2862 =item * $dt->set_formatter( $formatter )
2863
2864 Set the formatter for the object. See L<Formatters And
2865 Stringification> for details.
2866
2867 =back
2868
2869 =head3 Math Methods
2870
2871 Like the set methods, math related methods always return the object
2872 itself, to allow for chaining:
2873
2874   $dt->add( days => 1 )->subtract( seconds => 1 );
2875
2876 =over 4
2877
2878 =item * $dt->duration_class()
2879
2880 This returns C<DateTime::Duration>, but exists so that a subclass of
2881 C<DateTime.pm> can provide a different value.
2882
2883 =item * $dt->add_duration( $duration_object )
2884
2885 This method adds a C<DateTime::Duration> to the current datetime.  See
2886 the L<DateTime::Duration|DateTime::Duration> docs for more details.
2887
2888 =item * $dt->add( DateTime::Duration->new parameters )
2889
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.
2893
2894 =item * $dt->subtract_duration( $duration_object )
2895
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.
2899
2900 =item * $dt->subtract( DateTime::Duration->new parameters )
2901
2902 Like C<add()>, this is syntactic sugar for the C<subtract_duration()>
2903 method.
2904
2905 =item * $dt->subtract_datetime( $datetime )
2906
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:
2910
2911     2003-03-15 00:00:00.00000000
2912  -  2003-02-15 00:00:00.00000000
2913
2914  -------------------------------
2915
2916  = 1 month
2917
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.
2921
2922 The returned duration may have deltas for months, days, minutes,
2923 seconds, and nanoseconds.
2924
2925 =item * $dt->delta_md( $datetime )
2926
2927 =item * $dt->delta_days( $datetime )
2928
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.
2934
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.
2939
2940 Unlike the subtraction methods, B<these methods always return a
2941 positive (or zero) duration>.
2942
2943 =item * $dt->delta_ms( $datetime )
2944
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)
2948 duration>.
2949
2950 =item * $dt->subtract_datetime_absolute( $datetime )
2951
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.
2957
2958 =back
2959
2960 =head3 Class Methods
2961
2962 =over 4
2963
2964 =item * DateTime->DefaultLocale( $locale )
2965
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.
2968
2969 =item * DateTime->compare( $dt1, $dt2 )
2970
2971 =item * DateTime->compare_ignore_floating( $dt1, $dt2 )
2972
2973   $cmp = DateTime->compare( $dt1, $dt2 );
2974
2975   $cmp = DateTime->compare_ignore_floating( $dt1, $dt2 );
2976
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
2979 > $dt2.
2980
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.
2986
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:
2990
2991   @dates = sort { DateTime->compare_ignore_floating($a, $b) } @dates;
2992
2993 In this case, objects with a floating time zone will be sorted as if
2994 they were UTC times.
2995
2996 Since DateTime objects overload comparison operators, this:
2997
2998   @dates = sort @dates;
2999
3000 is equivalent to this:
3001
3002   @dates = sort { DateTime->compare($a, $b) } @dates;
3003
3004 DateTime objects can be compared to any other calendar class that
3005 implements the C<utc_rd_values()> method.
3006
3007 =back
3008
3009 =head2 How Datetime Math is Done
3010
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>.
3014
3015 =head3 Making Things Simple
3016
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:
3019
3020 =over 4
3021
3022 =item * use the floating time zone
3023
3024 If you do not care about time zones or leap seconds, use the
3025 "floating" timezone:
3026
3027   my $dt = DateTime->now( time_zone => 'floating' );
3028
3029 Math done on two objects in the floating time zone produces very
3030 predictable results.
3031
3032 =item * use UTC for all calculations
3033
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
3037 presentation:
3038
3039   my $dt = DateTime->new( %user_input, time_zone => $user_tz );
3040   $dt->set_time_zone('UTC');
3041
3042   # do various operations - store it, retrieve it, add, subtract, etc.
3043
3044   $dt->set_time_zone($user_tz);
3045   print $dt->datetime;
3046
3047 =item * math on non-UTC time zones
3048
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
3054 change.
3055
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>
3058
3059 =item * date vs datetime math
3060
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.
3065
3066 =item * subtract_datetime() and add_duration()
3067
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
3070 are always true:
3071
3072   $dt2 - $dt1 = $dur
3073   $dt1 + $dur = $dt2
3074   $dt2 - $dur = $dt1
3075
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
3079 always reversible.
3080
3081 =back
3082
3083 =head3 Adding a Duration to a Datetime
3084
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
3090 same as 60 seconds.
3091
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.
3095
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
3100 just works.
3101
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.
3104
3105   my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
3106
3107   $dt->add( months => 1, days => 1 );
3108
3109   # 2003-04-01 - the result
3110
3111 On the other hand, if we add months first, and then separately add
3112 days, we end up with March 29, 2003:
3113
3114   $dt->add( months => 1 )->add( days => 1 );
3115
3116   # 2003-03-29
3117
3118 We see similar strangeness when math crosses a DST boundary:
3119
3120   my $dt = DateTime->new( year => 2003, month => 4, day => 5,
3121                           hour => 1, minute => 58,
3122                           time_zone => "America/Chicago",
3123                         );
3124
3125   $dt->add( days => 1, minutes => 3 );
3126   # 2003-04-06 02:01:00
3127
3128   $dt->add( minutes => 3 )->add( days => 1 );
3129   # 2003-04-06 03:01:00
3130
3131 Note that if you converted the datetime object to UTC first you would
3132 get predictable results.
3133
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:
3136
3137  my $now = DateTime->now( time_zone => 'UTC' );
3138  my $later = $now->clone->add_duration($duration);
3139
3140  my $seconds_dur = $later->subtract_datetime_absolute($now);
3141
3142 This returns a duration which only contains seconds and nanoseconds.
3143
3144 If we were add the duration to a different datetime object we might
3145 get a different number of seconds.
3146
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.
3150
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()>.
3155
3156 =head3 Datetime Subtraction
3157
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:
3163
3164 The first of these probably makes the most sense:
3165
3166     my $dt1 = DateTime->new( year => 2003, month => 5, day => 6,
3167                              time_zone => 'America/Chicago',
3168                            );
3169     # not DST
3170
3171     my $dt2 = DateTime->new( year => 2003, month => 11, day => 6,
3172                              time_zone => 'America/Chicago',
3173                            );
3174     # is DST
3175
3176     my $dur = $dt2->subtract_datetime($dt1);
3177     # 6 months
3178
3179 Nice and simple.
3180
3181 This one is a little trickier, but still fairly logical:
3182
3183     my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
3184                              hour => 1, minute => 58,
3185                              time_zone => "America/Chicago",
3186                            );
3187     # is DST
3188
3189     my $dt2 = DateTime->new( year => 2003, month => 4, day => 7,
3190                              hour => 2, minute => 1,
3191                              time_zone => "America/Chicago",
3192                            );
3193     # not DST
3194
3195     my $dur = $dt2->subtract_datetime($dt1);
3196     # 2 days and 3 minutes
3197
3198 Which contradicts the result this one gives, even though they both
3199 make sense:
3200
3201     my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
3202                              hour => 1, minute => 58,
3203                              time_zone => "America/Chicago",
3204                            );
3205     # is DST
3206
3207     my $dt2 = DateTime->new( year => 2003, month => 4, day => 6,
3208                              hour => 3, minute => 1,
3209                              time_zone => "America/Chicago",
3210                            );
3211     # not DST
3212
3213     my $dur = $dt2->subtract_datetime($dt1);
3214     # 1 day and 3 minutes
3215
3216 This last example illustrates the "DST" exception mentioned earlier.
3217 The exception accounts for the fact 2003-04-06 only lasts 23 hours.
3218
3219 And finally:
3220
3221     my $dt2 = DateTime->new( year => 2003, month => 10, day => 26,
3222                              hour => 1,
3223                              time_zone => 'America/Chicago',
3224                            );
3225
3226     my $dt1 = $dt2->clone->subtract( hours => 1 );
3227
3228     my $dur = $dt2->subtract_datetime($dt1);
3229     # 60 minutes
3230
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.
3234
3235 =head3 Reversibility
3236
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.
3241
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:
3245
3246   my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
3247                            hour => 1, minute => 58,
3248                            time_zone => "America/Chicago",
3249                          );
3250
3251   my $dt2 = DateTime->new( year => 2003, month => 4, day => 6,
3252                            hour => 3, minute => 1,
3253                            time_zone => "America/Chicago",
3254                          );
3255
3256   my $dur = $dt2->subtract_datetime($dt1);
3257   # 1 day and 3 minutes
3258
3259   $dt1->add_duration($dur);
3260   # gives us $dt2
3261
3262   $dt2->subtract_duration($dur);
3263   # gives us 2003-04-05 02:58:00 - 1 hour later than $dt1
3264
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.
3268
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:
3272
3273   $dt2->subtract_duration( $dur->clock_duration )
3274       ->subtract_duration( $dur->calendar_duration );
3275
3276 =head3 Leap Seconds and Date Math
3277
3278 The presence of leap seconds can cause even more anomalies in date
3279 math.  For example, the following is a legal datetime:
3280
3281   my $dt = DateTime->new( year => 1972, month => 12, day => 31,
3282                           hour => 23, minute => 59, second => 60,
3283                           time_zone => 'UTC' );
3284
3285 If we do the following:
3286
3287  $dt->add( months => 1 );
3288
3289 Then the datetime is now "1973-02-01 00:00:00", because there is no
3290 23:59:60 on 1973-01-31.
3291
3292 Leap seconds also force us to distinguish between minutes and seconds
3293 during date math.  Given the following datetime:
3294
3295   my $dt = DateTime->new( year => 1972, month => 12, day => 31,
3296                           hour => 23, minute => 59, second => 30,
3297                           time_zone => 'UTC' );
3298
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.
3302
3303 Here are the results we get:
3304
3305   # 1972-12-31 23:59:30 - our starting datetime
3306
3307   $dt->clone->add( minutes => 1 );
3308   # 1973-01-01 00:00:30 - one minute later
3309
3310   $dt->clone->add( seconds => 60 );
3311   # 1973-01-01 00:00:29 - 60 seconds later
3312
3313   $dt->clone->add( seconds => 61 );
3314   # 1973-01-01 00:00:30 - 61 seconds later
3315
3316 =head3 Local vs. UTC and 24 hours vs. 1 day
3317
3318 When math crosses a daylight saving boundary, a single day may have
3319 more or less than 24 hours.
3320
3321 For example, if you do this:
3322
3323   my $dt = DateTime->new( year => 2003, month => 4, day => 5,
3324                           hour => 2,
3325                           time_zone => 'America/Chicago',
3326                         );
3327   $dt->add( days => 1 );
3328
3329 then you will produce an I<invalid> local time, and therefore an
3330 exception will be thrown.
3331
3332 However, this works:
3333
3334   my $dt = DateTime->new( year => 2003, month => 4, day => 5,
3335                           hour => 2,
3336                           time_zone => 'America/Chicago',
3337                         );
3338   $dt->add( hours => 24 );
3339
3340 and produces a datetime with the local time of "03:00".
3341
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!
3348
3349 =head2 Overloading
3350
3351 This module explicitly overloads the addition (+), subtraction (-),
3352 string and numeric comparison operators.  This means that the
3353 following all do sensible things:
3354
3355   my $new_dt = $dt + $duration_obj;
3356
3357   my $new_dt = $dt - $duration_obj;
3358
3359   my $duration_obj = $dt - $new_dt;
3360
3361   foreach my $dt ( sort @dts ) { ... }
3362
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.
3366
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.
3371
3372 The module also overloads stringification to use the C<iso8601()>
3373 method.
3374
3375 =head2 Formatters And Stringification
3376
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.
3380
3381 Any of the constructor methods can accept a formatter argument:
3382
3383   my $formatter = DateTime::Format::Strptime->new(...);
3384   my $dt = DateTime->new(year => 2004, formatter => $formatter);
3385
3386 Or, you can set it afterwards:
3387
3388   $dt->set_formatter($formatter);
3389   $formatter = $dt->formatter();
3390
3391 Once you set the formatter, the overloaded stringification method will
3392 use the formatter. If unspecified, the C<iso8601()> method is used.
3393
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.
3397
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.
3401
3402 =head2 strftime Patterns
3403
3404 The following patterns are allowed in the format string given to the
3405 C<< $dt->strftime() >> method:
3406
3407 =over 4
3408
3409 =item * %a
3410
3411 The abbreviated weekday name.
3412
3413 =item * %A
3414
3415 The full weekday name.
3416
3417 =item * %b
3418
3419 The abbreviated month name.
3420
3421 =item * %B
3422
3423 The full month name.
3424
3425 =item * %c
3426
3427 The default datetime format for the object's locale.
3428
3429 =item * %C
3430
3431 The century number (year/100) as a 2-digit integer.
3432
3433 =item * %d
3434
3435 The day of the month as a decimal number (range 01 to 31).
3436
3437 =item * %D
3438
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!
3442
3443 =item * %e
3444
3445 Like %d, the day of the month as a decimal number, but a leading zero
3446 is replaced by a space.
3447
3448 =item * %F
3449
3450 Equivalent to %Y-%m-%d (the ISO 8601 date format)
3451
3452 =item * %G
3453
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)
3458
3459 =item * %g
3460
3461 Like %G, but without century, i.e., with a 2-digit year (00-99).
3462
3463 =item * %h
3464
3465 Equivalent to %b.
3466
3467 =item * %H
3468
3469 The hour as a decimal number using a 24-hour clock (range 00 to 23).
3470
3471 =item * %I
3472
3473 The hour as a decimal number using a 12-hour clock (range 01 to 12).
3474
3475 =item * %j
3476
3477 The day of the year as a decimal number (range 001 to 366).
3478
3479 =item * %k
3480
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.)
3483
3484 =item * %l
3485
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.)
3488
3489 =item * %m
3490
3491 The month as a decimal number (range 01 to 12).
3492
3493 =item * %M
3494
3495 The minute as a decimal number (range 00 to 59).
3496
3497 =item * %n
3498
3499 A newline character.
3500
3501 =item * %N
3502
3503 The fractional seconds digits. Default is 9 digits (nanoseconds).
3504
3505   %3N   milliseconds (3 digits)
3506   %6N   microseconds (6 digits)
3507   %9N   nanoseconds  (9 digits)
3508
3509 =item * %p
3510
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'.
3514
3515 =item * %P
3516
3517 Like %p but in lowercase: `am' or `pm' or a corresponding string for
3518 the current locale.
3519
3520 =item * %r
3521
3522 The time in a.m.  or p.m. notation.  In the POSIX locale this is
3523 equivalent to `%I:%M:%S %p'.
3524
3525 =item * %R
3526
3527 The time in 24-hour notation (%H:%M). (SU) For a version including the
3528 seconds, see %T below.
3529
3530 =item * %s
3531
3532 The number of seconds since the epoch.
3533
3534 =item * %S
3535
3536 The second as a decimal number (range 00 to 61).
3537
3538 =item * %t
3539
3540 A tab character.
3541
3542 =item * %T
3543
3544 The time in 24-hour notation (%H:%M:%S).
3545
3546 =item * %u
3547
3548 The day of the week as a decimal, range 1 to 7, Monday being 1.  See
3549 also %w.
3550
3551 =item * %U
3552
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
3555 also %V and %W.
3556
3557 =item * %V
3558
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.
3563
3564 =item * %w
3565
3566 The day of the week as a decimal, range 0 to 6, Sunday being 0.  See
3567 also %u.
3568
3569 =item * %W
3570
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.
3573
3574 =item * %x
3575
3576 The default date format for the object's locale.
3577
3578 =item * %X
3579
3580 The default time format for the object's locale.
3581
3582 =item * %y
3583
3584 The year as a decimal number without a century (range 00 to 99).
3585
3586 =item * %Y
3587
3588 The year as a decimal number including the century.
3589
3590 =item * %z
3591
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").
3594
3595 =item * %Z
3596
3597 The time zone or name or abbreviation.
3598
3599 =item * %%
3600
3601 A literal `%' character.
3602
3603 =item * %{method}
3604
3605 Any method name may be specified using the format C<%{method}> name
3606 where "method" is a valid C<DateTime.pm> object method.
3607
3608 =back
3609
3610 =head2 CLDR Patterns
3611
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.
3616
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 ('').
3621
3622   'Today is ' EEEE
3623   'It is now' h 'o''clock' a
3624
3625 Spaces and any non-letter text will always be passed through as-is.
3626
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.
3631
3632 However, CLDR often uses five of a letter to represent the narrow form
3633 of a pattern. This inconsistency is necessary for backwards
3634 compatibility.
3635
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.
3640
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.
3644
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>.
3648
3649 The output of a CLDR pattern is always localized, when applicable.
3650
3651 CLDR provides the following patterns:
3652
3653 =over 4
3654
3655 =item * G{1,3}
3656
3657 The abbreviated era (BC, AD).
3658
3659 =item * GGGG
3660
3661 The wide era (Before Christ, Anno Domini).
3662
3663 =item * GGGGG
3664
3665 The narrow era, if it exists (and it mostly doesn't).
3666
3667 =item * y and y{3,}
3668
3669 The year, zero-prefixed as needed. Negative years will start with a "-",
3670 and this will be included in the length calculation.
3671
3672 In other, words the "yyyyy" pattern will format year -1234 as "-1234", not
3673 "-01234".
3674
3675 =item * yy
3676
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.
3679
3680 =item * Y{1,}
3681
3682 The week of the year, from C<< $dt->week_year() >>.
3683
3684 =item * u{1,}
3685
3686 Same as "y" except that "uu" is not a special case.
3687
3688 =item * Q{1,2}
3689
3690 The quarter as a number (1..4).
3691
3692 =item * QQQ
3693
3694 The abbreviated format form for the quarter.
3695
3696 =item * QQQQ
3697
3698 The wide format form for the quarter.
3699
3700 =item * q{1,2}
3701
3702 The quarter as a number (1..4).
3703
3704 =item * qqq
3705
3706 The abbreviated stand-alone form for the quarter.
3707
3708 =item * qqqq
3709
3710 The wide stand-alone form for the quarter.
3711
3712 =item * M{1,2]
3713
3714 The numerical month.
3715
3716 =item * MMM
3717
3718 The abbreviated format form for the month.
3719
3720 =item * MMMM
3721
3722 The wide format form for the month.
3723
3724 =item * MMMMM
3725
3726 The narrow format form for the month.
3727
3728 =item * L{1,2]
3729
3730 The numerical month.
3731
3732 =item * LLL
3733
3734 The abbreviated stand-alone form for the month.
3735
3736 =item * LLLL
3737
3738 The wide stand-alone form for the month.
3739
3740 =item * LLLLL
3741
3742 The narrow stand-alone form for the month.
3743
3744 =item * w{1,2}
3745
3746 The week of the year, from C<< $dt->week_number() >>.
3747
3748 =item * W
3749
3750 The week of the month, from C<< $dt->week_of_month() >>.
3751
3752 =item * d{1,2}
3753
3754 The numeric day of of the month.
3755
3756 =item * D{1,3}
3757
3758 The numeric day of of the year.
3759
3760 =item * F
3761
3762 The day of the week in the month, from C<< $dt->weekday_of_month() >>.
3763
3764 =item * g{1,}
3765
3766 The modified Julian day, from C<< $dt->mjd() >>.
3767
3768 =item * E{1,3} and eee
3769
3770 The abbreviated format form for the day of the week.
3771
3772 =item * EEEE and eeee
3773
3774 The wide format form for the day of the week.
3775
3776 =item * EEEEE and eeeee
3777
3778 The narrow format form for the day of the week.
3779
3780 =item * e{1,2}
3781
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.
3786
3787 =item * c
3788
3789 The numeric day of the week from 1 to 7, treating Monday as the first
3790 of the week, regardless of locale.
3791
3792 =item * ccc
3793
3794 The abbreviated stand-alone form for the day of the week.
3795
3796 =item * cccc
3797
3798 The wide stand-alone form for the day of the week.
3799
3800 =item * ccccc
3801
3802 The narrow format form for the day of the week.
3803
3804 =item * a
3805
3806 The localized form of AM or PM for the time.
3807
3808 =item * h{1,2}
3809
3810 The hour from 1-12.
3811
3812 =item * H{1,2}
3813
3814 The hour from 0-23.
3815
3816 =item * K{1,2}
3817
3818 The hour from 0-11.
3819
3820 =item * k{1,2}
3821
3822 The hour from 1-24.
3823
3824 =item * j{1,2}
3825
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
3828 "H{1,2}".
3829
3830 =item * m{1,2}
3831
3832 The minute.
3833
3834 =item * s{1,2}
3835
3836 The second.
3837
3838 =item * S{1,}
3839
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.
3843
3844 =item * A{1,}
3845
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.
3848
3849 =item * z{1,3}
3850
3851 The time zone short name.
3852
3853 =item * zzzz
3854
3855 The time zone long name.
3856
3857 =item * Z{1,3}
3858
3859 The time zone short name and the offset as one string, so something
3860 like "CDT-0500".
3861
3862 =item * ZZZZ
3863
3864 The time zone long name.
3865
3866 =item * v{1,3}
3867
3868 The time zone short name.
3869
3870 =item * vvvv
3871
3872 The time zone long name.
3873
3874 =item * V{1,3}
3875
3876 The time zone short name.
3877
3878 =item * VVVV
3879
3880 The time zone long name.
3881
3882 =back
3883
3884 =head1 DateTime.pm and Storable
3885
3886 DateTime implements Storable hooks in order to reduce the size of a
3887 serialized DateTime object.
3888
3889 =head1 KNOWN BUGS
3890
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.
3895
3896 If you don't plan to use infinite datetimes you can probably ignore
3897 this.  This will be fixed (somehow) in future versions.
3898
3899 =head1 SUPPORT
3900
3901 Support for this module is provided via the datetime@perl.org email
3902 list. See http://datetime.perl.org/?MailingList for details.
3903
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.
3907
3908 =head1 DONATIONS
3909
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.
3914
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
3918 interests me.
3919
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
3923 best.
3924
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>
3928
3929 =head1 AUTHOR
3930
3931 Dave Rolsky <autarch@urth.org>
3932
3933 However, please see the CREDITS file for more details on who I really
3934 stole all the code from.
3935
3936 =head1 COPYRIGHT
3937
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.
3941
3942 Portions of the code in this distribution are derived from other
3943 works.  Please see the CREDITS file for more details.
3944
3945 The full text of the license can be found in the LICENSE file included
3946 with this module.
3947
3948 =head1 SEE ALSO
3949
3950 datetime@perl.org mailing list
3951
3952 http://datetime.perl.org/
3953
3954 =cut