Alternative Time::Local algorithm that uses matemathical formula
[p5sagit/p5-mst-13.2.git] / lib / Time / Local.pm
1 package Time::Local;
2 use 5.006;
3 require Exporter;
4 use Carp;
5 use strict;
6 use integer;
7
8 our $VERSION    = '1.03';
9 our @ISA        = qw( Exporter );
10 our @EXPORT     = qw( timegm timelocal );
11 our @EXPORT_OK  = qw( timegm_nocheck timelocal_nocheck );
12
13 my @MonthDays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
14
15 # Determine breakpoint for rolling century
16 my $ThisYear     = (localtime())[5];
17 my $Breakpoint   = ($ThisYear + 50) % 100;
18 my $NextCentury  = $ThisYear - $ThisYear % 100;
19    $NextCentury += 100 if $Breakpoint < 50;
20 my $Century      = $NextCentury - 100;
21
22 my (%Options, %Cheat);
23
24 # Determine the EPOC day for this machine
25 my $Epoc = 0; $Epoc = _daygm(gmtime(0));
26 %Cheat=(); # clear the cache as epoc has changed
27
28 my $MaxDay = do {
29   no integer;
30   int((~0>>1-43200)/86400)-1;
31 };
32
33
34 sub _daygm {
35     $_[3] + ($Cheat{pack("ss",@_[4,5])} ||= do {
36         my $month = ($_[4] + 10) % 12;
37         my $year = $_[5] + 1900 - $month/10;
38         365*$year + $year/4 - $year/100 + $year/400 + ($month*306 + 5)/10 - $Epoc
39     });
40 }
41
42
43 sub _timegm {
44     $_[0]  +  60 * $_[1]  +  3600 * $_[2]  +  86400 * &_daygm;
45 }
46
47
48 sub timegm {
49     my ($sec,$min,$hour,$mday,$month,$year) = @_;
50
51     if ($year >= 1000) {
52         $year -= 1900;
53     }
54     elsif ($year < 100 and $year >= 0) {
55         $year += ($year > $Breakpoint) ? $Century : $NextCentury;
56     }
57
58     unless ($Options{no_range_check}) {
59         if (abs($year) >= 0x7fff) {
60             $year += 1900;
61             croak "Cannot handle date ($sec, $min, $hour, $mday, $month, $year)";
62         }
63
64         croak "Month '$month' out of range 0..11" if $month > 11 or $month < 0;
65
66         my $md = $MonthDays[$month];
67         ++$md unless $month != 1 or $year % 4 or !($year % 400);
68
69         croak "Day '$mday' out of range 1..$md"   if $mday  > $md  or $mday  < 1;
70         croak "Hour '$hour' out of range 0..23"   if $hour  > 23   or $hour  < 0;
71         croak "Minute '$min' out of range 0..59"  if $min   > 59   or $min   < 0;
72         croak "Second '$sec' out of range 0..59"  if $sec   > 59   or $sec   < 0;
73     }
74
75     my $days = _daygm(undef, undef, undef, $mday, $month, $year);
76
77     unless ($Options{no_range_check} or abs($days) < $MaxDay) {
78         $year += 1900;
79         croak "Cannot handle date ($sec, $min, $hour, $mday, $month, $year)";
80     }
81
82     $sec + 60*$min + 3600*$hour + 86400*$days;
83 }
84
85
86 sub timegm_nocheck {
87     local $Options{no_range_check} = 1;
88     &timegm;
89 }
90
91
92 sub timelocal {
93     my $ref_t = &timegm;
94     my $loc_t = _timegm(localtime($ref_t));
95
96     # Is there a timezone offset from GMT or are we done
97     my $zone_off = $ref_t - $loc_t
98         or return $loc_t;
99
100     # Adjust for timezone
101     $loc_t = $ref_t + $zone_off;
102
103     # Are we close to a DST change or are we done
104     my $dst_off = $ref_t - _timegm(localtime($loc_t))
105         or return $loc_t;
106
107     # Adjust for DST change
108     $loc_t + $dst_off;
109 }
110
111
112 sub timelocal_nocheck {
113     local $Options{no_range_check} = 1;
114     &timelocal;
115 }
116
117 1;
118
119 __END__
120
121 =head1 NAME
122
123 Time::Local - efficiently compute time from local and GMT time
124
125 =head1 SYNOPSIS
126
127     $time = timelocal($sec,$min,$hour,$mday,$mon,$year);
128     $time = timegm($sec,$min,$hour,$mday,$mon,$year);
129
130 =head1 DESCRIPTION
131
132 These routines are the inverse of built-in perl functions localtime()
133 and gmtime().  They accept a date as a six-element array, and return
134 the corresponding time(2) value in seconds since the Epoch (Midnight,
135 January 1, 1970).  This value can be positive or negative.
136
137 It is worth drawing particular attention to the expected ranges for
138 the values provided.  The value for the day of the month is the actual day
139 (ie 1..31), while the month is the number of months since January (0..11).
140 This is consistent with the values returned from localtime() and gmtime().
141
142 The timelocal() and timegm() functions perform range checking on the
143 input $sec, $min, $hour, $mday, and $mon values by default.  If you'd
144 rather they didn't, you can explicitly import the timelocal_nocheck()
145 and timegm_nocheck() functions.
146
147         use Time::Local 'timelocal_nocheck';
148
149         {
150             # The 365th day of 1999
151             print scalar localtime timelocal_nocheck 0,0,0,365,0,99;
152
153             # The twenty thousandth day since 1970
154             print scalar localtime timelocal_nocheck 0,0,0,20000,0,70;
155
156             # And even the 10,000,000th second since 1999!
157             print scalar localtime timelocal_nocheck 10000000,0,0,1,0,99;
158         }
159
160 Your mileage may vary when trying these with minutes and hours,
161 and it doesn't work at all for months.
162
163 Strictly speaking, the year should also be specified in a form consistent
164 with localtime(), i.e. the offset from 1900.
165 In order to make the interpretation of the year easier for humans,
166 however, who are more accustomed to seeing years as two-digit or four-digit
167 values, the following conventions are followed:
168
169 =over 4
170
171 =item *
172
173 Years greater than 999 are interpreted as being the actual year,
174 rather than the offset from 1900.  Thus, 1963 would indicate the year
175 Martin Luther King won the Nobel prize, not the year 2863.
176
177 =item *
178
179 Years in the range 100..999 are interpreted as offset from 1900, 
180 so that 112 indicates 2012.  This rule also applies to years less than zero
181 (but see note below regarding date range).
182
183 =item *
184
185 Years in the range 0..99 are interpreted as shorthand for years in the
186 rolling "current century," defined as 50 years on either side of the current
187 year.  Thus, today, in 1999, 0 would refer to 2000, and 45 to 2045,
188 but 55 would refer to 1955.  Twenty years from now, 55 would instead refer
189 to 2055.  This is messy, but matches the way people currently think about
190 two digit dates.  Whenever possible, use an absolute four digit year instead.
191
192 =back
193
194 The scheme above allows interpretation of a wide range of dates, particularly
195 if 4-digit years are used.  
196
197 Please note, however, that the range of dates that can be actually be handled
198 depends on the size of an integer (time_t) on a given platform.  
199 Currently, this is 32 bits for most systems, yielding an approximate range 
200 from Dec 1901 to Jan 2038.
201
202 Both timelocal() and timegm() croak if given dates outside the supported
203 range.
204
205 =head1 IMPLEMENTATION
206
207 These routines are quite efficient and yet are always guaranteed to agree
208 with localtime() and gmtime().  We manage this by caching the start times
209 of any months we've seen before.  If we know the start time of the month,
210 we can always calculate any time within the month.  The start times
211 are calculated using a mathematical formula. Unlike other algorithms
212 that do multiple calls to gmtime().
213
214 timelocal() is implemented using the same cache.  We just assume that we're
215 translating a GMT time, and then fudge it when we're done for the timezone
216 and daylight savings arguments.  Note that the timezone is evaluated for
217 each date because countries occasionally change their official timezones.
218 Assuming that localtime() corrects for these changes, this routine will
219 also be correct.
220
221 =head1 BUGS
222
223 The whole scheme for interpreting two-digit years can be considered a bug.
224
225 The proclivity to croak() is probably a bug.
226
227 =cut
228