Debian Codegraph @

lib/Date/Parse.pm

raw
1 # Copyright (c) 1995-2009 Graham Barr. This program is free
2 # software; you can redistribute it and/or modify it under the same terms
3 # as Perl itself.
4
5 package Date::Parse;
6
7 require 5.000;
8 use strict;
9 use Time::Local;
10 use Carp;
11 use Time::Zone;
12 use Exporter;
13
14 our @ISA = qw(Exporter);
15 our @EXPORT = qw(&strtotime &str2time &strptime);
16
17 our $VERSION = '2.35'; # VERSION: generated
18 # ABSTRACT: Parse date strings into time values
19
20 my %month = (
21 january => 0,
22 february => 1,
23 march => 2,
24 april => 3,
25 may => 4,
26 june => 5,
27 july => 6,
28 august => 7,
29 september => 8,
30 sept => 8,
31 october => 9,
32 november => 10,
33 december => 11,
34 );
35
36 my %day = (
37 sunday => 0,
38 monday => 1,
39 tuesday => 2,
40 tues => 2,
41 wednesday => 3,
42 wednes => 3,
43 thursday => 4,
44 thur => 4,
45 thurs => 4,
46 friday => 5,
47 saturday => 6,
48 );
49
50 my @suf = (qw(th st nd rd th th th th th th)) x 3;
51 @suf[11,12,13] = qw(th th th);
52
53 #Abbreviations
54
55 map { $month{substr($_,0,3)} = $month{$_} } keys %month;
56 map { $day{substr($_,0,3)} = $day{$_} } keys %day;
57
58 my $strptime = <<'ESQ';
59 my %month = map { lc $_ } %$mon_ref;
60 my $daypat = join("|", map { lc $_ } reverse sort keys %$day_ref);
61 my $monpat = join("|", reverse sort keys %month);
62 my $sufpat = join("|", reverse sort map { lc $_ } @$suf_ref);
63
64 my %ampm = (
65 'a' => 0, # AM
66 'p' => 12, # PM
67 );
68
69 my($AM, $PM) = (0,12);
70
71 sub {
72
73 my $dtstr = lc shift;
74 my $merid = 24;
75
76 my($century,$year,$month,$day,$hh,$mm,$ss,$zone,$dst,$frac);
77
78 $zone = tz_offset(shift) if @_;
79
80 1 while $dtstr =~ s#\([^\(\)]*\)# #o;
81
82 $dtstr =~ s#(\A|\n|\Z)# #sog;
83
84 # ignore day names
85 $dtstr =~ s#([\d\w\s])[\.\,]\s#$1 #sog;
86 $dtstr =~ s/(?<!\d),|,(?!\d)/ /g;
87 $dtstr =~ s#($daypat)\s*(den\s)?\b# #o;
88 # Time: 12:00 or 12:00:00 with optional am/pm
89
90 return unless $dtstr =~ /\S/;
91
92 # ISO compact: YYYYMMDD without delimiter (month and day must be exactly 2 digits)
93 if ($dtstr =~ s/\s(\d{4})(\d\d)(\d\d)(?:[-Tt ](\d\d?)(?:([-:]?)(\d\d?)(?:\5(\d\d?)(?:[.,](\d+))?)?)?)?(?=\D)/ /) {
94 ($year,$month,$day,$hh,$mm,$ss,$frac) = ($1,$2-1,$3,$4,$6,$7,$8);
95 }
96 # Date with explicit delimiter: YYYY[-:]MM[-:]DD
97 elsif ($dtstr =~ s/\s(\d{4})([-:])(\d\d?)\2(\d\d?)(?:[-Tt ](\d\d?)(?:([-:]?)(\d\d?)(?:\6(\d\d?)(?:[.,](\d+))?)?)?)?(?=\D)/ /) {
98 ($year,$month,$day,$hh,$mm,$ss,$frac) = ($1,$3-1,$4,$5,$7,$8,$9);
99 }
100
101 # default C++ boost timestamp is effectively %Y-%b-%d %H:%M:%S.%f
102 # details: https://svn.boost.org/trac/boost/ticket/8839
103 if ($dtstr =~ s/\s(\d{4})([-:]?)(\w{3,})\2(\d\d?)(?:[-Tt ](\d\d?)(?:([-:]?)(\d\d?)(?:\6(\d\d?)(?:[.,](\d+))?)?)?)?(?=\D)/ /) {
104 ($year,$month,$day,$hh,$mm,$ss,$frac) = ($1,$month{$3},$4,$5,$7,$8,$9);
105 }
106
107 unless (defined $hh) {
108 if ($dtstr =~ s#[:\s](\d\d?):(\d\d?)(:(\d\d?)(?:\.\d+)?)?(z)?\s*(?:([ap])\.?m?\.?)?\s# #o) {
109 ($hh,$mm,$ss) = ($1,$2,$4);
110 $zone = 0 if $5;
111 $merid = $ampm{$6} if $6;
112 }
113
114 # Time: 12 am
115
116 elsif ($dtstr =~ s#\s(\d\d?)\s*([ap])\.?m?\.?\s# #o) {
117 ($hh,$mm,$ss) = ($1,0,0);
118 $merid = $ampm{$2};
119 }
120 }
121
122 if (defined $hh and $hh <= 12 and $dtstr =~ s# ([ap])\.?m?\.?\s# #o) {
123 $merid = $ampm{$1};
124 }
125
126
127 unless (defined $year) {
128 # Date: 12-June-96 (using - . or /)
129
130 if ($dtstr =~ s#\s(\d\d?)([\-\./])($monpat)(\2(\d\d+))?\s# #o) {
131 ($month,$day) = ($month{$3},$1);
132 $year = $5 if $5;
133 }
134
135 # Date: 12-12-96 (using '-', '.' or '/' )
136
137 elsif ($dtstr =~ s#\s(\d+)([\-\./])(\d\d?)(\2(\d+))?\s# #o) {
138 ($month,$day) = ($1 - 1,$3);
139
140 if ($5) {
141 $year = $5;
142 # Possible match for 1995-01-24 (short mainframe date format);
143 ($year,$month,$day) = ($1, $3 - 1, $5) if $month > 12;
144 return if length($year) > 2 and $year < 1901;
145 }
146 }
147 elsif ($dtstr =~ s#\s(\d+)\s*($sufpat)?\s*($monpat)# #o) {
148 ($month,$day) = ($month{$3},$1);
149 }
150 elsif ($dtstr =~ s#($monpat)\s*(\d+)\s*($sufpat)?\s# #o) {
151 $month = $month{$1};
152 if ($2 > 31) { $year = $2 } else { $day = $2 }
153 }
154 elsif ($dtstr =~ s#($monpat)([\/-])(\d+)[\/-]# #o) {
155 ($month,$day) = ($month{$1},$3);
156 }
157
158 # Date: 961212 (YYMMDD — only consume if month is in range 1-12)
159
160 elsif ($dtstr =~ /\s(\d\d)(\d\d)(\d\d)\s/o && $2 >= 1 && $2 <= 12) {
161 $dtstr =~ s/\s(\d\d)(\d\d)(\d\d)\s/ /;
162 ($year,$month,$day) = ($1,$2-1,$3);
163 }
164
165 $year = $1 if !defined($year) and $dtstr =~ s#\s(\d{2}(\d{2})?)[\s\.,]# #o;
166
167 }
168
169 # Zone
170
171 $dst = 1 if $dtstr =~ s#\bdst\b##o;
172
173 if ($dtstr =~ s#\s"?([a-z]{3,4})(dst|\d+[a-z]*|_[a-z]+)?"?\s# #o) {
174 $dst = 1 if $2 and $2 eq 'dst';
175 $zone = tz_offset($1);
176 return unless defined $zone;
177 }
178 elsif ($dtstr =~ s#\s([a-z]{3,4})?([\-\+]?)-?(\d\d?):?(\d\d)?(00)?\s# #o) {
179 my $m = defined($4) ? "$2$4" : 0;
180 my $h = "$2$3";
181 $zone = defined($1) ? tz_offset($1) : 0;
182 return unless defined $zone;
183 $zone += 60 * ($m + (60 * $h));
184 }
185
186 if ($dtstr =~ /\S/) {
187 # now for some dumb dates
188 if ($dtstr =~ s/^\s*(ut?|z)\s*$//) {
189 $zone = 0;
190 }
191 elsif ($dtstr =~ s#\s([a-z]{3,4})?([\-\+]?)-?(\d\d?)(\d\d)?(00)?\s# #o) {
192 my $m = defined($4) ? "$2$4" : 0;
193 my $h = "$2$3";
194 $zone = defined($1) ? tz_offset($1) : 0;
195 return unless defined $zone;
196 $zone += 60 * ($m + (60 * $h));
197 }
198
199 return if $dtstr =~ /\S/o;
200 }
201
202 if (defined $hh) {
203 if ($hh == 12) {
204 $hh = 0 if $merid == $AM;
205 }
206 elsif ($merid == $PM) {
207 $hh += 12;
208 }
209 }
210
211 if (defined $year && $year >= 100) {
212 $century = int($year / 100);
213 $year -= 1900;
214 }
215
216 $zone += 3600 if defined $zone && $dst;
217 $ss += "0.$frac" if $frac;
218
219 # Reject inputs that produced only a timezone with no date/time components.
220 # A bare number like '1' or '+0500' gets consumed by the timezone regex,
221 # leaving no meaningful date or time information — these are not valid dates.
222 return unless defined $hh || defined $mm || defined $ss
223 || defined $day || defined $month || defined $year;
224
225 return ($ss,$mm,$hh,$day,$month,$year,$zone,$century);
226 }
227 ESQ
228
229 our ($day_ref, $mon_ref, $suf_ref, $obj);
230
231 sub gen_parser
232 {
233 local($day_ref,$mon_ref,$suf_ref,$obj) = @_;
234
235 if($obj)
236 {
237 my $obj_strptime = $strptime;
238 substr($obj_strptime,index($strptime,"sub")+6,0) = <<'ESQ';
239 shift; # package
240 ESQ
241 my $sub = eval "$obj_strptime" or die $@;
242 return $sub;
243 }
244
245 eval "$strptime" or die $@;
246
247 }
248
249 *strptime = gen_parser(\%day,\%month,\@suf);
250
251 sub str2time
252 {
253 my $now = @_ > 2 ? splice(@_, 2, 1) : time;
254 my @t = strptime(@_);
255
256 return undef
257 unless @t;
258
259 my($ss,$mm,$hh,$day,$month,$year,$zone, $century) = @t;
260 my @lt = localtime($now);
261
262 $hh ||= 0;
263 $mm ||= 0;
264 $ss ||= 0;
265
266 my $frac = $ss - int($ss);
267 $ss = int $ss;
268
269 $month = $lt[4]
270 unless(defined $month);
271
272 $day = $lt[3]
273 unless(defined $day);
274
275 unless (defined $year) {
276 my $is_future = $month > $lt[4]
277 || ($month == $lt[4] && $day > $lt[3]);
278 $year = $is_future ? ($lt[5] - 1) : $lt[5];
279 }
280
281 # we were given a 4 digit year, so let's keep using those
282 $year += 1900 if defined $century;
283
284 # Normalize two-digit years to 4-digit before passing to Time::Local.
285 # Time::Local's own windowing varies across versions, so we do it ourselves.
286 # Convention: 69-99 -> 1969-1999, 0-68 -> 2000-2068 (POSIX strptime behavior).
287 # Note: first-century dates (years 1-99 AD) are not representable through
288 # str2time — same limitation as POSIX strptime.
289 $year += ($year >= 69 ? 1900 : 2000) if $year < 100;
290
291 return undef
292 unless($month <= 11 && $day >= 1 && $day <= 31
293 && $hh <= 23 && $mm <= 59 && $ss <= 59);
294
295 my $result;
296
297 if (defined $zone) {
298 $result = eval {
299 local $SIG{__DIE__} = sub {}; # Ick!
300 timegm($ss,$mm,$hh,$day,$month,$year);
301 };
302 return undef
303 if !defined $result
304 or $result == -1
305 && join("",$ss,$mm,$hh,$day,$month,$year)
306 ne "595923311169";
307 # Detect integer overflow: post-1970 dates must produce a non-negative epoch
308 return undef if $result < 0 && $year >= 1970;
309 $result -= $zone;
310 }
311 else {
312 $result = eval {
313 local $SIG{__DIE__} = sub {}; # Ick!
314 timelocal($ss,$mm,$hh,$day,$month,$year);
315 };
316 return undef
317 if !defined $result
318 or $result == -1
319 && join("",$ss,$mm,$hh,$day,$month,$year)
320 ne join("",(localtime(-1))[0..5]);
321 # Detect integer overflow: post-1970 dates must produce a non-negative epoch
322 # Use 1971 to avoid false positives from timezone offsets near epoch 0
323 return undef if $result < 0 && $year >= 1971;
324 }
325
326 return $result + $frac;
327 }
328
329 1;
330
331 __END__
332
333 =pod
334
335 =encoding UTF-8
336
337 =head1 NAME
338
339 Date::Parse - Parse date strings into time values
340
341 =head1 VERSION
342
343 version 2.35
344
345 =head1 SYNOPSIS
346
347 use Date::Parse;
348
349 my $date = "Wed, 16 Jun 94 07:29:35 CST";
350 my $time = str2time($date);
351
352 my ($ss,$mm,$hh,$day,$month,$year,$zone) = strptime($date);
353
354 =head1 DESCRIPTION
355
356 C<Date::Parse> provides two routines for parsing date strings into time values.
357
358 =over 4
359
360 =item str2time(DATE [, ZONE [, EPOCH]])
361
362 C<str2time> parses C<DATE> and returns a unix time value, or undef upon failure.
363 C<ZONE>, if given, specifies the timezone to assume when parsing if the
364 date string does not specify a timezone.
365 C<EPOCH>, if given, is a unix epoch value used as the reference time when
366 filling in missing date components (month, day, or year). Defaults to
367 C<time()>. Useful when the current system clock cannot be trusted or when
368 parsing dates relative to a known reference point.
369
370 =item strptime(DATE [, ZONE])
371
372 C<strptime> takes the same arguments as str2time but returns an array of
373 values C<($ss,$mm,$hh,$day,$month,$year,$zone,$century)>. Elements are only
374 defined if they could be extracted from the date string. An empty array is
375 returned upon failure.
376
377 The return values follow the same conventions as Perl's built-in C<localtime>
378 and C<gmtime> functions:
379
380 =over 4
381
382 =item C<$month>
383
384 0-indexed: 0 = January, 1 = February, ..., 11 = December.
385
386 =item C<$year>
387
388 Years since 1900. For example, the year 2015 is returned as C<115>, and 1995
389 is returned as C<95>. To recover the full 4-digit year: C<$year + 1900>.
390
391 =item C<$zone>
392
393 Timezone offset in seconds from UTC, or C<undef> if no timezone was specified
394 in the input string.
395
396 =item C<$century>
397
398 Defined only when a 4-digit year was present in the input. Its value is
399 C<int($full_year / 100)> (e.g. C<20> for the year 2015). When C<$century> is
400 defined, C<$year + 1900> gives the original 4-digit year.
401
402 =back
403
404 For example, C<strptime("2015-01-24T09:08:17")> returns:
405
406 ($ss, $mm, $hh, $day, $month, $year, $zone, $century)
407 ( 17, 8, 9, 24, 0, 115, undef, 20 )
408 # ^--- January (0-indexed)
409 # ^--- 2015 - 1900
410 # ^--- not in input
411 # ^--- int(2015/100)
412
413 =back
414
415 =head1 NAME
416
417 Date::Parse - Parse date strings into time values
418
419 =head1 MULTI-LANGUAGE SUPPORT
420
421 Date::Parse is capable of parsing dates in several languages, these include
422 English, French, German and Italian.
423
424 $lang = Date::Language->new('German');
425 $lang->str2time("25 Jun 1996 21:09:55 +0100");
426
427 =head1 EXAMPLE DATES
428
429 Below is a sample list of dates that are known to be parsable with Date::Parse
430
431 1995-01-24T09:08:17.1823213 ISO-8601
432 Wed, 16 Jun 94 07:29:35 CST Comma and day name are optional
433 Thu, 13 Oct 94 10:13:13 -0700
434 Wed, 9 Nov 1994 09:50:32 -0500 (EST) Text in ()'s will be ignored.
435 21 dec 17:05 Will be parsed in the current time zone
436 21-dec 17:05
437 21/dec 17:05
438 21/dec/93 17:05
439 1999 10:02:18 "GMT"
440 16 Nov 94 22:28:20 PST
441
442 =head1 BUGS
443
444 When both the month and the date are specified in the date as numbers
445 they are always parsed assuming that the month number comes before the
446 date. This is the usual format used in American dates.
447
448 The reason why it is like this and not dynamic is that it must be
449 deterministic. Several people have suggested using the current locale,
450 but this will not work as the date being parsed may not be in the format
451 of the current locale.
452
453 My plans to address this, which will be in a future release, is to allow
454 the programmer to state what order they want these values parsed in.
455
456 =head1 AUTHOR
457
458 Graham Barr <[email protected]>
459
460 =head1 COPYRIGHT
461
462 Copyright (c) 1995-2009 Graham Barr. This program is free
463 software; you can redistribute it and/or modify it under the same terms
464 as Perl itself.
465
466 =head1 AUTHOR
467
468 Graham <[email protected]>
469
470 =head1 COPYRIGHT AND LICENSE
471
472 This software is copyright (c) 2020 by Graham Barr.
473
474 This is free software; you can redistribute it and/or modify it under
475 the same terms as the Perl 5 programming language system itself.
476
477 =cut