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