Add lib to @INC so that ./perl t/op/local.t works.
[p5sagit/p5-mst-13.2.git] / lib / Time / Local.pm
1 package Time::Local;
2
3 require Exporter;
4 use Carp;
5 use Config;
6 use strict;
7 use integer;
8
9 use vars qw( $VERSION @ISA @EXPORT @EXPORT_OK );
10 $VERSION   = '1.15';
11
12 @ISA       = qw( Exporter );
13 @EXPORT    = qw( timegm timelocal );
14 @EXPORT_OK = qw( timegm_nocheck timelocal_nocheck );
15
16 my @MonthDays = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
17
18 # Determine breakpoint for rolling century
19 my $ThisYear    = ( localtime() )[5];
20 my $Breakpoint  = ( $ThisYear + 50 ) % 100;
21 my $NextCentury = $ThisYear - $ThisYear % 100;
22 $NextCentury += 100 if $Breakpoint < 50;
23 my $Century = $NextCentury - 100;
24 my $SecOff  = 0;
25
26 my ( %Options, %Cheat );
27
28 use constant SECS_PER_MINUTE => 60;
29 use constant SECS_PER_HOUR   => 3600;
30 use constant SECS_PER_DAY    => 86400;
31
32 my $MaxInt = ( ( 1 << ( 8 * $Config{intsize} - 2 ) ) -1 ) * 2 + 1;
33 my $MaxDay = int( ( $MaxInt - ( SECS_PER_DAY / 2 ) ) / SECS_PER_DAY ) - 1;
34
35 if ( $^O eq 'MacOS' ) {
36     # time_t is unsigned...
37     $MaxInt = ( 1 << ( 8 * $Config{intsize} ) ) - 1;
38 }
39 else {
40     $MaxInt = ( ( 1 << ( 8 * $Config{intsize} - 2 ) ) - 1 ) * 2 + 1;
41 }
42
43 # Determine the EPOC day for this machine
44 my $Epoc = 0;
45 if ( $^O eq 'vos' ) {
46     # work around posix-977 -- VOS doesn't handle dates in the range
47     # 1970-1980.
48     $Epoc = _daygm( 0, 0, 0, 1, 0, 70, 4, 0 );
49 }
50 elsif ( $^O eq 'MacOS' ) {
51     $MaxDay *=2 if $^O eq 'MacOS';  # time_t unsigned ... quick hack?
52     # MacOS time() is seconds since 1 Jan 1904, localtime
53     # so we need to calculate an offset to apply later
54     $Epoc = 693901;
55     $SecOff = timelocal( localtime(0)) - timelocal( gmtime(0) ) ;
56     $Epoc += _daygm( gmtime(0) );
57 }
58 else {
59     $Epoc = _daygm( gmtime(0) );
60 }
61
62 %Cheat = ();    # clear the cache as epoc has changed
63
64 sub _daygm {
65
66     # This is written in such a byzantine way in order to avoid
67     # lexical variables and sub calls, for speed
68     return $_[3] + (
69         $Cheat{ pack( 'ss', @_[ 4, 5 ] ) } ||= do {
70             my $month = ( $_[4] + 10 ) % 12;
71             my $year  = $_[5] + 1900 - $month / 10;
72
73             ( ( 365 * $year )
74               + ( $year / 4 )
75               - ( $year / 100 )
76               + ( $year / 400 )
77               + ( ( ( $month * 306 ) + 5 ) / 10 )
78             )
79             - $Epoc;
80         }
81     );
82 }
83
84 sub _timegm {
85     my $sec =
86         $SecOff + $_[0] + ( SECS_PER_MINUTE * $_[1] ) + ( SECS_PER_HOUR * $_[2] );
87
88     return $sec + ( SECS_PER_DAY * &_daygm );
89 }
90
91 sub timegm {
92     my ( $sec, $min, $hour, $mday, $month, $year ) = @_;
93
94     # Need to check leap year before altering the value
95     my $leap_year = _is_leap_year($year);
96
97     if ( $year >= 1000 ) {
98         $year -= 1900;
99     }
100     elsif ( $year < 100 and $year >= 0 ) {
101         $year += ( $year > $Breakpoint ) ? $Century : $NextCentury;
102     }
103
104     unless ( $Options{no_range_check} ) {
105         if ( abs($year) >= 0x7fff ) {
106             $year += 1900;
107             croak
108                 "Cannot handle date ($sec, $min, $hour, $mday, $month, *$year*)";
109         }
110
111         croak "Month '$month' out of range 0..11"
112             if $month > 11
113             or $month < 0;
114
115         my $md = $MonthDays[$month];
116         ++$md
117             if $month == 1 && $leap_year;
118
119         croak "Day '$mday' out of range 1..$md"  if $mday > $md or $mday < 1;
120         croak "Hour '$hour' out of range 0..23"  if $hour > 23  or $hour < 0;
121         croak "Minute '$min' out of range 0..59" if $min > 59   or $min < 0;
122         croak "Second '$sec' out of range 0..59" if $sec > 59   or $sec < 0;
123     }
124
125     my $days = _daygm( undef, undef, undef, $mday, $month, $year );
126
127     unless ($Options{no_range_check} or abs($days) < $MaxDay) {
128         my $msg = '';
129         $msg .= "Day too big - $days > $MaxDay\n" if $days > $MaxDay;
130
131         $year += 1900;
132         $msg .=  "Cannot handle date ($sec, $min, $hour, $mday, $month, $year)";
133
134         croak $msg;
135     }
136
137     return $sec
138            + $SecOff
139            + ( SECS_PER_MINUTE * $min )
140            + ( SECS_PER_HOUR * $hour )
141            + ( SECS_PER_DAY * $days );
142 }
143
144 sub _is_leap_year {
145     return 0 if $_[0] % 4;
146     return 1 if $_[0] % 100;
147     return 0 if $_[0] % 400;
148
149     return 1;
150 }
151
152 sub timegm_nocheck {
153     local $Options{no_range_check} = 1;
154     return &timegm;
155 }
156
157 sub timelocal {
158     my $ref_t = &timegm;
159     my $loc_for_ref_t = _timegm( localtime($ref_t) );
160
161     my $zone_off = $loc_for_ref_t - $ref_t
162         or return $loc_for_ref_t;
163
164     # Adjust for timezone
165     my $loc_t = $ref_t - $zone_off;
166
167     # Are we close to a DST change or are we done
168     my $dst_off = $ref_t - _timegm( localtime($loc_t) );
169
170     # If this evaluates to true, it means that the value in $loc_t is
171     # the _second_ hour after a DST change where the local time moves
172     # backward.
173     if ( ! $dst_off &&
174          ( ( $ref_t - SECS_PER_HOUR ) - _timegm( localtime( $loc_t - SECS_PER_HOUR ) ) < 0 )
175        ) {
176         return $loc_t - SECS_PER_HOUR;
177     }
178
179     # Adjust for DST change
180     $loc_t += $dst_off;
181
182     return $loc_t if $dst_off > 0;
183
184     # If the original date was a non-extent gap in a forward DST jump,
185     # we should now have the wrong answer - undo the DST adjustment
186     my ( $s, $m, $h ) = localtime($loc_t);
187     $loc_t -= $dst_off if $s != $_[0] || $m != $_[1] || $h != $_[2];
188
189     return $loc_t;
190 }
191
192 sub timelocal_nocheck {
193     local $Options{no_range_check} = 1;
194     return &timelocal;
195 }
196
197 1;
198
199 __END__
200
201 =head1 NAME
202
203 Time::Local - efficiently compute time from local and GMT time
204
205 =head1 SYNOPSIS
206
207     $time = timelocal($sec,$min,$hour,$mday,$mon,$year);
208     $time = timegm($sec,$min,$hour,$mday,$mon,$year);
209
210 =head1 DESCRIPTION
211
212 This module provides functions that are the inverse of built-in perl
213 functions C<localtime()> and C<gmtime()>. They accept a date as a
214 six-element array, and return the corresponding C<time(2)> value in
215 seconds since the system epoch (Midnight, January 1, 1970 GMT on Unix,
216 for example). This value can be positive or negative, though POSIX
217 only requires support for positive values, so dates before the
218 system's epoch may not work on all operating systems.
219
220 It is worth drawing particular attention to the expected ranges for
221 the values provided. The value for the day of the month is the actual
222 day (ie 1..31), while the month is the number of months since January
223 (0..11). This is consistent with the values returned from
224 C<localtime()> and C<gmtime()>.
225
226 =head1 FUNCTIONS
227
228 This module exports two functions by default, C<timelocal()> and
229 C<timegm()>.
230
231 The C<timelocal()> and C<timegm()> functions perform range checking on
232 the input $sec, $min, $hour, $mday, and $mon values by default.
233
234 If you are working with data you know to be valid, you can speed your
235 code up by using the "nocheck" variants, C<timelocal_nocheck()> and
236 C<timegm_nocheck()>. These variants must be explicitly imported.
237
238     use Time::Local 'timelocal_nocheck';
239
240     # The 365th day of 1999
241     print scalar localtime timelocal_nocheck 0,0,0,365,0,99;
242
243 If you supply data which is not valid (month 27, second 1,000) the
244 results will be unpredictable (so don't do that).
245
246 =head2 Year Value Interpretation
247
248 Strictly speaking, the year should be specified in a form consistent
249 with C<localtime()>, i.e. the offset from 1900. In order to make the
250 interpretation of the year easier for humans, however, who are more
251 accustomed to seeing years as two-digit or four-digit values, the
252 following conventions are followed:
253
254 =over 4
255
256 =item *
257
258 Years greater than 999 are interpreted as being the actual year,
259 rather than the offset from 1900. Thus, 1964 would indicate the year
260 Martin Luther King won the Nobel prize, not the year 3864.
261
262 =item *
263
264 Years in the range 100..999 are interpreted as offset from 1900, so
265 that 112 indicates 2012. This rule also applies to years less than
266 zero (but see note below regarding date range).
267
268 =item *
269
270 Years in the range 0..99 are interpreted as shorthand for years in the
271 rolling "current century," defined as 50 years on either side of the
272 current year. Thus, today, in 1999, 0 would refer to 2000, and 45 to
273 2045, but 55 would refer to 1955. Twenty years from now, 55 would
274 instead refer to 2055. This is messy, but matches the way people
275 currently think about two digit dates. Whenever possible, use an
276 absolute four digit year instead.
277
278 =back
279
280 The scheme above allows interpretation of a wide range of dates,
281 particularly if 4-digit years are used.
282
283 =head2 Limits of time_t
284
285 The range of dates that can be actually be handled depends on the size
286 of C<time_t> (usually a signed integer) on the given
287 platform. Currently, this is 32 bits for most systems, yielding an
288 approximate range from Dec 1901 to Jan 2038.
289
290 Both C<timelocal()> and C<timegm()> croak if given dates outside the
291 supported range.
292
293 =head2 Ambiguous Local Times (DST)
294
295 Because of DST changes, there are many time zones where the same local
296 time occurs for two different GMT times on the same day. For example,
297 in the "Europe/Paris" time zone, the local time of 2001-10-28 02:30:00
298 can represent either 2001-10-28 00:30:00 GMT, B<or> 2001-10-28
299 01:30:00 GMT.
300
301 When given an ambiguous local time, the timelocal() function should
302 always return the epoch for the I<earlier> of the two possible GMT
303 times.
304
305 =head2 Non-Existent Local Times (DST)
306
307 When a DST change causes a locale clock to skip one hour forward,
308 there will be an hour's worth of local times that don't exist. Again,
309 for the "Europe/Paris" time zone, the local clock jumped from
310 2001-03-25 01:59:59 to 2001-03-25 03:00:00.
311
312 If the C<timelocal()> function is given a non-existent local time, it
313 will simply return an epoch value for the time one hour later.
314
315 =head2 Negative Epoch Values
316
317 Negative epoch (C<time_t>) values are not officially supported by the
318 POSIX standards, so this module's tests do not test them. On some
319 systems, they are known not to work. These include MacOS (pre-OSX) and
320 Win32.
321
322 On systems which do support negative epoch values, this module should
323 be able to cope with dates before the start of the epoch, down the
324 minimum value of time_t for the system.
325
326 =head1 IMPLEMENTATION
327
328 These routines are quite efficient and yet are always guaranteed to
329 agree with C<localtime()> and C<gmtime()>. We manage this by caching
330 the start times of any months we've seen before. If we know the start
331 time of the month, we can always calculate any time within the month.
332 The start times are calculated using a mathematical formula. Unlike
333 other algorithms that do multiple calls to C<gmtime()>.
334
335 The C<timelocal()> function is implemented using the same cache. We
336 just assume that we're translating a GMT time, and then fudge it when
337 we're done for the timezone and daylight savings arguments. Note that
338 the timezone is evaluated for each date because countries occasionally
339 change their official timezones. Assuming that C<localtime()> corrects
340 for these changes, this routine will also be correct.
341
342 =head1 BUGS
343
344 The whole scheme for interpreting two-digit years can be considered a
345 bug.
346
347 =head1 SUPPORT
348
349 Support for this module is provided via the datetime@perl.org email
350 list. See http://lists.perl.org/ for more details.
351
352 Please submit bugs to the CPAN RT system at
353 http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Time-Local or via email
354 at bug-time-local@rt.cpan.org.
355
356 =head1 AUTHOR
357
358 This module is based on a Perl 4 library, timelocal.pl, that was
359 included with Perl 4.036, and was most likely written by Tom
360 Christiansen.
361
362 The current version was written by Graham Barr.
363
364 It is now being maintained separately from the Perl core by Dave
365 Rolsky, <autarch@urth.org>.
366
367 =cut