qbit/Date.pm untested

filter: Statementstmt 0.0% 0 / 213 Branchbran 0.0% 0 / 86 Conditioncond 0.0% 0 / 62 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 401 CC 41 SCAR 48.9
CC
41
Cov
0%
name2dates
380.0
name2date
110.0
trdate
30.0
CRAP 133.3
1  
2 =head1 Name
3  
4 qbit::Array - Functions to manipulate dates.
5  
6 =cut
7  
8 package qbit::Date;
9 $qbit::Date::VERSION = '2.7';
10 use strict;
11 use warnings;
12 use utf8;
13  
14 use base qw(Exporter);
15  
16 use POSIX qw(strftime);
17 use Time::Local;
18 use Date::Calc qw(Add_Delta_YMDHMS Add_Delta_YM Monday_of_Week Week_of_Year Delta_YMDHMS Delta_Days Days_in_Month);
19  
20 use qbit::Exceptions;
21 use qbit::Array;
22 use qbit::GetText;
23  
24 BEGIN {
25 our (@EXPORT, @EXPORT_OK);
26  
27 @EXPORT = qw(
28 trdate curdate date_add date_sub name2date name2dates
29 dates2array dates_delta dates_delta_days compare_dates
30 check_date format_date is_date_in_future is_date_in_past
31 );
32 @EXPORT_OK = @EXPORT;
33 }
34  
35 our %TR_HS = (
36 norm => {
37 '>' => sub {[@{$_[0]}]},
38 '<' => sub {[@{$_[0]}]},
39 },
40 db => {
41 '>' => sub {sprintf('%04d-%02d-%02d', @{$_[0]}[0 .. 2])},
42 '<' => sub {
43 shift =~ /\A(\d{4})-(\d{2})-(\d{2})\z/
44 ? [$1, $2, $3, 0, 0, 0]
45 : [0, 0, 0, 0, 0, 0];
46 },
47 },
48 db_time => {
49 '>' => sub {
50 sprintf("%04d-%02d-%02d %02d:%02d:%02d", @{$_[0]});
51 },
52 '<' => sub {
53 shift =~ /\A(\d{4})-(\d{2})-(\d{2})(?:(?:\s+|T)(\d{1,2}):(\d{1,2}):(\d{1,2}))?\z/
54 ? [$1, $2, $3, $4 // 0, $5 // 0, $6 // 0]
55 : [0, 0, 0, 0, 0, 0];
56 },
57 },
58 sec => {
59 '>' => sub {
60 $_[0]->[1] < 1
61 ? 0
62 : timelocal($_[0]->[5] || 0, $_[0]->[4] || 0, $_[0]->[3] || 0, $_[0]->[2], ($_[0]->[1] - 1), $_[0]->[0]);
63 },
64 '<' => sub {
65 my @dt = localtime(shift);
66 [$dt[5] + 1900, $dt[4] + 1, $dt[3], $dt[2], $dt[1], $dt[0]];
67 },
68 },
69 days_in_month => {
70 '>' => sub {
71 Days_in_Month($_[0]->[0], $_[0]->[1]);
72 },
73 },
74 );
75  
76 =head1 Functions
77  
78 =head2 trdate
79  
80 B<Arguments:>
81  
82 =over
83  
84 =item
85  
86 B<$iformat> - string, input format;
87  
88 =item
89  
90 B<$oformat> - string, output format. One of:
91  
92 =over
93  
94 =item
95  
96 B<norm> - array ref, ['year', 'month (1-12)', 'day (1-31)', 'hour (0-23)', 'minute (0-59)', 'second (0-59)'];
97  
98 =item
99  
100 B<db_time> - string, 'YYYY-MM-DD hh:mm:ss';
101  
102 =item
103  
104 B<sec> - number, seconds like in C<localtime>;
105  
106 =item
107  
108 B<days_in_month> - number, days in month. Cannot convert from this type to other.
109  
110 =back
111  
112 =item
113  
114 B<$date> - scalar, date in input format.
115  
116 =back
117  
118 B<Return value:> scalar, date in output format. C<undef> if conversion has errors.
119  
120 Convert date from C<iformat> to C<oformat>.
121  
122 trdate(db => sec => '2000-01-01');
123  
124 =cut
125  
126 sub trdate {
127 my ($iformat, $oformat, $date) = @_;
128  
129 throw gettext('Unknown iformat "%s"', $iformat) unless exists($TR_HS{$iformat});
130 throw gettext('Unknown oformat "%s"', $oformat) unless exists($TR_HS{$oformat});
131 throw gettext('Cannott convert from format "%s"', $iformat)
132 unless exists($TR_HS{$iformat}->{'<'});
133  
134 my $norm_date = $TR_HS{$iformat}->{'<'}($date);
135 return undef if @$norm_date == 6 && !grep {$_ != 0} @$norm_date;
136 $_ = int($_) foreach @$norm_date;
137 return $TR_HS{$oformat}->{'>'}($norm_date);
138 }
139  
140 =head2 curdate
141  
142 B<Arguments as hash:>
143  
144 =over
145  
146 =item
147  
148 B<oformat> - string, output format, see L</trdate>.
149  
150 =back
151  
152 B<Return value:> scalar, current date in output format.
153  
154 curdate(oformat => 'db');
155  
156 =cut
157  
158 sub curdate {
159 my (%opts) = @_;
160  
161 my ($sec, $min, $hour, $day, $month, $year, $wday, $yday, $isdst) = localtime(time());
162 $year += 1900;
163 $month++;
164  
165 my $res = [$year, $month, $day, $hour, $min, $sec];
166  
167 return exists($opts{'oformat'}) ? trdate(norm => $opts{'oformat'} => $res) : $res;
168 }
169  
170 =head2 date_add
171  
172 B<Arguments:>
173  
174 =over
175  
176 =item
177  
178 B<$date> - scalar, date;
179  
180 =item
181  
182 B<%opts> - hash, additional arguments:
183  
184 =over
185  
186 =item
187  
188 B<iformat> - string, input format, default - 'norm';
189  
190 =item
191  
192 B<oformat> - string, output format, default - 'norm';
193  
194 =item
195  
196 B<second> - number, quantity of seconds to add;
197  
198 =item
199  
200 B<minute> - number, quantity of minutes to add;
201  
202 =item
203  
204 B<hour> - number, quantity of hours to add;
205  
206 =item
207  
208 B<day> - number, quantity of days to add;
209  
210 =item
211  
212 B<week> - number, quantity of weeks to add;
213  
214 =item
215  
216 B<month> - number, quantity of months to add;
217  
218 =item
219  
220 B<year> - number, quantity of years to add;
221  
222 =back
223  
224 =back
225  
226 B<Return value:> scalar, date in output format.
227  
228 date_add('2000-01-01', day => 12, hour => 5, iformat => 'db', oformat => 'db');
229  
230 =cut
231  
232 sub date_add {
233 my ($date, %opts) = @_;
234  
235 $date = trdate(($opts{'iformat'} || 'norm') => 'norm' => $date);
236  
237 $opts{'day'} += $opts{'week'} * 7 if exists($opts{'week'});
238 my @res = ();
239 if ($opts{month} || $opts{year}) {
240  
241 # do not warp into next month (year)
242 @res = (Add_Delta_YM(@$date[0, 1, 2], $opts{year} // 0, $opts{month} // 0), 0, 0, 0);
243 @res = Add_Delta_YMDHMS(@res, 0, 0, map {$opts{$_} || 0} qw(day hour minute second));
244 } else {
245 @res = Add_Delta_YMDHMS(@$date, map {$opts{$_} || 0} qw(year month day hour minute second));
246 }
247  
248 return exists($opts{'oformat'}) ? trdate(norm => $opts{'oformat'} => \@res) : \@res;
249 }
250  
251 =head2 date_sub
252  
253 See L</date_add>
254  
255 =cut
256  
257 sub date_sub {
258 my ($date, %opts) = @_;
259  
260 $opts{$_} = -($opts{$_} || 0) foreach qw(year month week day hour minute second);
261  
262 return date_add($date, %opts);
263 }
264  
265 =head2 name2date
266  
267 B<Arguments:>
268  
269 =over
270  
271 =item
272  
273 B<$name> - string, date caption. Available values:
274  
275 =over
276  
277 lastyesterday
278  
279 lasttoday
280  
281 daybeforeyesterday
282  
283 yesterday
284  
285 today or day
286  
287 tomorrow
288  
289 dayaftertomorrow;
290  
291 =back
292  
293 =item
294  
295 B<%opts> - hash, additional arguments:
296  
297 =over
298  
299 =item
300  
301 B<oformat>: string, output format, default - 'norm'.
302  
303 =back
304  
305 =back
306  
307 B<Return value:> scalar, date in output format. C<undef> unless known name.
308  
309 name2date('yesterday', oformat => 'db');
310  
311 =cut
312  
313 sub name2date {
314 my ($name, %opts) = @_;
315  
316 my $res =
317 $name eq 'lastyesterday' ? date_sub(curdate(), day => 8)
318 : $name eq 'lasttoday' ? date_sub(curdate(), day => 7)
319 : $name eq 'daybeforeyesterday' ? date_sub(curdate(), day => 2)
320 : $name eq 'yesterday' ? date_sub(curdate(), day => 1)
321 : $name eq 'today' ? curdate()
322 : $name eq 'day' ? curdate()
323 : $name eq 'tomorrow' ? date_add(curdate(), day => 1)
324 : $name eq 'dayaftertomorrow' ? date_add(curdate(), day => 2)
325 : return;
326  
327 return exists($opts{'oformat'}) ? trdate(norm => $opts{'oformat'} => $res) : $res;
328 }
329  
330 =head2 name2dates
331  
332 B<Arguments:>
333  
334 =over
335  
336 =item
337  
338 B<$name> - string, period caption. One of:
339  
340 =over
341  
342 =item
343  
344 Any from L</name2date>;
345  
346 =item
347  
348 B<week, sevendays, last7days>: last 7 days, including today;
349  
350 =item
351  
352 B<thisweek>: current week, from Monday to today;
353  
354 =item
355  
356 B<lastweek, pastweek>: past week, from Monday to Sunday;
357  
358 =item
359  
360 B<tendays>: last 10 days, including today;
361  
362 =item
363  
364 B<lastmonth, pastmonth>: past month, from 1th to (28|29|30|31)th;
365  
366 =item
367  
368 B<month>: current month, from 1th to (28|29|30|31)th;
369  
370 =item
371  
372 B<thismonth>: current month, from 1th to today;
373  
374 =item
375  
376 B<year, thisyear>: current year, from January 1th to December 31th;
377  
378 =item
379  
380 B<{N}days>: last {N} days, including today, {N} - numer, quantity of days;
381  
382 =item
383  
384 B<pastpastweek>: week before past week, from Monday to Sunday;
385  
386 =item
387  
388 B<past{N}days>: last {N} days before {N} days, {N} - number of days;
389  
390 =item
391  
392 B<pastpastmonth>: month before past month, from 1th to (28|29|30|31)th;
393  
394 =item
395  
396 B<pastyear>: past year, from January 1th to December 31th;
397  
398 =item
399  
400 B<twoyearsago>: year before past year, from January 1th to December 31th;
401  
402 =back
403  
404 =item
405  
406 B<$fd> - scalar, start date. Return if unknown period name;
407  
408 =item
409  
410 B<$td> - scalar, end date. Return if unknown period name;
411  
412 =item
413  
414 B<%opts> - hash, additional arguments:
415  
416 =over
417  
418 =item
419  
420 B<iformat>: string, input format for C<$fd> and C<$td>, default - 'norm';
421  
422 =item
423  
424 B<oformat>: string, output format, default - 'norm'.
425  
426 =back
427  
428 =back
429  
430 B<Return value>: array, (start_date, end_date).
431  
432 ($fd, $td) = name2date('pastyear', [], [], oformat => 'db'); # ('2012-01-01', '2012-12-31')
433 ($fd, $td) = name2date('other', '2000-01-01', '2000-01-03', iformat => 'db', oformat => 'db'); # ('2000-01-01', '2000-01-03')
434  
435 =cut
436  
437 sub name2dates {
438 my ($name, $fd, $td, %opts) = @_;
439  
440 $fd = trdate(($opts{'iformat'} || 'norm') => 'norm' => $fd);
441 $td = trdate(($opts{'iformat'} || 'norm') => 'norm' => $td);
442  
443 if (my $date_by_name = name2date($name)) {
444 $fd = [@$date_by_name];
445 $td = [@$date_by_name];
446 } elsif (in_array($name, [qw(week sevendays last7days)])) {
447 $td = curdate();
448 $fd = date_sub($td, day => 6);
449 } elsif ($name eq 'thisweek') {
450 $fd = curdate();
451 $td = curdate();
452 @$fd[0 .. 2] = Monday_of_Week(Week_of_Year(@$fd[0 .. 2]));
453 } elsif (in_array($name, [qw(lastweek pastweek)])) {
454 $fd = date_sub(curdate(), week => 1);
455 @$fd[0 .. 2] = Monday_of_Week(Week_of_Year(@$fd[0 .. 2]));
456 $td = date_add($fd, day => 6);
457 } elsif ($name eq 'tendays') {
458 $td = curdate();
459 $fd = date_sub($td, day => 9);
460 } elsif (in_array($name, [qw(lastmonth pastmonth)])) {
461 $fd = date_sub(curdate(), month => 1);
462 $td = [@$fd];
463 $fd->[2] = 1;
464 $td->[2] = trdate(norm => days_in_month => $td);
465 } elsif ($name eq 'month') {
466 $fd = curdate();
467 $td = curdate();
468 $fd->[2] = 1;
469 $td->[2] = trdate(norm => days_in_month => $td);
470 } elsif ($name eq 'thismonth') {
471 $fd = curdate();
472 $td = curdate();
473 $fd->[2] = 1;
474 } elsif ($name eq 'last30days') {
475 $td = curdate();
476 $fd = date_sub($td, day => 30);
477 } elsif (in_array($name, [qw(year thisyear)])) {
478 $fd = curdate();
479 $td = curdate();
480 $fd->[1] = $fd->[2] = 1;
481 ($td->[1], $td->[2]) = (12, 31);
482 } elsif ($name =~ /^(\d+)days$/) {
483 $td = curdate();
484 $fd = date_sub($td, day => $1 - 1);
485 } elsif ($name eq 'pastpastweek') {
486 $fd = date_sub(curdate(), week => 2);
487 @$fd[0 .. 2] = Monday_of_Week(Week_of_Year(@$fd[0 .. 2]));
488 $td = date_add($fd, day => 6);
489 } elsif ($name =~ /^past(\d+)days$/) {
490 $fd = date_sub(curdate(), day => $1 * 2 - 1);
491 $td = date_sub(curdate(), day => $1);
492 } elsif ($name eq 'pastpastmonth') {
493 $fd = date_sub(curdate(), month => 2);
494 $td = [@$fd];
495 $fd->[2] = 1;
496 $td->[2] = trdate(norm => days_in_month => $td);
497 } elsif ($name eq 'pastyear') {
498 $fd = date_sub(curdate(), year => 1);
499 $td = [@$fd];
500 $fd->[1] = $fd->[2] = 1;
501 ($td->[1], $td->[2]) = (12, 31);
502 } elsif ($name eq 'twoyearsago') {
503 $fd = date_sub(curdate(), year => 2);
504 $td = [@$fd];
505 $fd->[1] = $fd->[2] = 1;
506 ($td->[1], $td->[2]) = (12, 31);
507 }
508  
509 $fd->[3] = $fd->[4] = $fd->[5] = 0;
510 ($td->[3], $td->[4], $td->[5]) = (23, 59, 59);
511  
512 $fd = trdate(norm => $opts{'oformat'} => $fd) if exists($opts{'oformat'});
513 $td = trdate(norm => $opts{'oformat'} => $td) if exists($opts{'oformat'});
514 return ($fd, $td);
515 }
516  
517 =head2 dates2array
518  
519 B<Arguments:>
520  
521 =over
522  
523 =item
524  
525 B<$fd> - scalar, start date;
526  
527 =item
528  
529 B<$td> - scalar, end date;
530  
531 =item
532  
533 B<%opts> - hash, additional arguments:
534  
535 =over
536  
537 =item
538  
539 B<iformat>: string, input format, default - 'norm';
540  
541 =item
542  
543 B<oformat>: string, output format, default - 'norm';
544  
545 =item
546  
547 B<interval>: string, step size: day, week, month, year. Default day.
548  
549 =back
550  
551 =back
552  
553 B<Return value>: array of scalars.
554  
555 my @dates = dates2array('2001-01-01', '2001-01-04', iformat => 'db', oformat => 'db');
556  
557 =cut
558  
559 sub dates2array {
560 my ($fd, $td, %opts) = @_;
561  
562 $opts{'interval'} = 'day' unless $opts{'interval'} && in_array($opts{'interval'}, [qw(day week month year)]);
563  
564 my $start_dt = trdate(($opts{'iformat'} || 'norm') => db_time => $fd);
565 my $end_dt = trdate(($opts{'iformat'} || 'norm') => db_time => $td);
566  
567 my @res = ();
568 while ($start_dt le $end_dt) {
569 push(@res, trdate(db_time => ($opts{'oformat'} || 'norm') => $start_dt));
570 $start_dt = date_add($start_dt, iformat => 'db_time', oformat => 'db_time', $opts{'interval'} => 1);
571 }
572  
573 return @res;
574 }
575  
576 =head2 dates_delta
577  
578 B<Arguments:>
579  
580 =over
581  
582 =item
583  
584 B<$fd> - scalar, start date;
585  
586 =item
587  
588 B<$td> - scalar, end date;
589  
590 =item
591  
592 B<%opts> - hash, additional arguments:
593  
594 =over
595  
596 =item
597  
598 B<iformat>: string, input format, default - 'norm'.
599  
600 =back
601  
602 =back
603  
604 B<Return value:> array ref, [years, months, days, hours, minutes, seconds].
605  
606 =cut
607  
608 sub dates_delta {
609 my ($fd, $td, %opts) = @_;
610  
611 $fd = trdate(($opts{'iformat'} || 'norm') => 'norm' => $fd);
612 $td = trdate(($opts{'iformat'} || 'norm') => 'norm' => $td);
613  
614 return [Delta_YMDHMS(@$fd, @$td)];
615 }
616  
617 =head2 dates_delta_days
618  
619 B<Arguments:> See L</dates_delta>
620  
621 B<Return value:> number, days from C<$fd> to C<$td>.
622  
623 =cut
624  
625 sub dates_delta_days {
626 my ($fd, $td, %opts) = @_;
627  
628 $fd = trdate(($opts{'iformat'} || 'norm') => 'norm' => $fd);
629 $td = trdate(($opts{'iformat'} || 'norm') => 'norm' => $td);
630  
631 return Delta_Days(@$fd[0 .. 2], @$td[0 .. 2]);
632 }
633  
634 =head2 compare_dates
635  
636 B<Arguments:>
637  
638 =over
639  
640 =item
641  
642 B<$dt1> - scalar, first date;
643  
644 =item
645  
646 B<$dt2> - scalar, second date;
647  
648 =item
649  
650 B<%opts> - hash, additional arguments:
651  
652 =over
653  
654 =item
655  
656 B<iformat1>: string, input format for first date, default - 'norm'.
657  
658 =item
659  
660 B<iformat2>: string, input format for second date, default - 'norm'.
661  
662 =back
663  
664 =back
665  
666 B<Return value:>
667  
668 =over
669  
670 =item
671  
672 B<-1>: C<$dt1 < $dt2>;
673  
674 =item
675  
676 B<0>: C<$dt1 = $dt2>;
677  
678 =item
679  
680 B<1>: C<< $dt1 > $dt2 >>.
681  
682 =back
683  
684 compare_dates($dt1, $dt2, iformat1 => 'db', iformat2 => 'norm')
685  
686 =cut
687  
688 sub compare_dates {
689 my ($dt1, $dt2, %opts) = @_;
690  
691 return trdate($opts{'iformat1'} || 'norm', "sec", $dt1) <=> trdate($opts{'iformat2'} || 'norm', "sec", $dt2);
692  
693 }
694  
695 =head2 format_date
696  
697 B<Arguments:>
698  
699 =over
700  
701 =item
702  
703 B<$date> - scalar, date;
704  
705 =item
706  
707 B<$format> - string, output format;
708  
709 =item
710  
711 B<%opts> - hash, additional arguments:
712  
713 =over
714  
715 =item
716  
717 B<iformat>: string, input format for date, default - 'norm'.
718  
719 =back
720  
721 =back
722  
723 B<Formaters:>
724  
725 %a Abbreviated weekday name Thu
726 %A Full weekday name Thursday
727 %b Abbreviated month name Aug
728 %B Full month name August
729 %c Date and time representation Thu Aug 23 14:55:02 2001
730 %d Day of the month (01-31) 23
731 %H Hour in 24h format (00-23) 14
732 %I Hour in 12h format (01-12) 02
733 %j Day of the year (001-366) 235
734 %m Month as a decimal number (01-12) 08
735 %M Minute (00-59) 55
736 %p AM or PM designation PM
737 %S Second (00-61) 02
738 %U Week number with the first Sunday as the first day of week one (00-53) 33
739 %w Weekday as a decimal number with Sunday as 0 (0-6) 4
740 %W Week number with the first Monday as the first day of week one (00-53) 34
741 %x Date representation 08/23/01
742 %X Time representation 14:55:02
743 %y Year, last two digits (00-99) 01
744 %Y Year 2001
745 %Z Timezone name or abbreviation CDT
746 %% A % sign %
747  
748 B<Return value:> string
749  
750 format_date('2001-01-01', '%Y %B', iformat => 'db');
751  
752 =cut
753  
754 sub format_date {
755 my ($date, $format, %opts) = @_;
756  
757 my $fdate = strftime($format, localtime(trdate($opts{'iformat'} || 'norm', "sec", $date)));
758  
759 utf8::decode($fdate);
760  
761 return $fdate;
762 }
763  
764 =head2 is_date_in_future
765  
766 B<Arguments:>
767  
768 =over
769  
770 =item
771  
772 B<$date> - scalar, date;
773  
774 =item
775  
776 B<%opts> - hash, additional arguments:
777  
778 =over
779  
780 =item
781  
782 B<iformat>: string, input format for date, default - 'norm'.
783  
784 =back
785  
786 =back
787  
788 B<Return value:> boolean.
789  
790 is_date_in_future($date, iformat => 'db')
791  
792 =cut
793  
794 sub is_date_in_future {
795 my ($date, %opts) = @_;
796  
797 return compare_dates(
798 $date,
799 curdate(oformat => 'sec'),
800 iformat1 => $opts{iformat} ? $opts{iformat} : 'norm',
801 iformat2 => 'sec',
802 ) == 1;
803  
804 }
805  
806 =head2 is_date_in_past
807  
808 See L</is_date_in_future>
809  
810 =cut
811  
812 sub is_date_in_past {
813 my ($date, %opts) = @_;
814  
815 return compare_dates(
816 $date,
817 curdate(oformat => 'sec'),
818 iformat1 => $opts{iformat} ? $opts{iformat} : 'norm',
819 iformat2 => 'sec',
820 ) == -1;
821  
822 }
823  
824 =head2 check_date
825  
826 B<Arguments:>
827  
828 =over
829  
830 =item
831  
832 B<$date> - scalar, date;
833  
834 =item
835  
836 B<%opts> - hash, additional arguments:
837  
838 =over
839  
840 =item B<iformat>: string, input format for date, default - 'norm'.
841  
842 =back
843  
844 =back
845  
846 B<Return value:> boolean.
847  
848 check_date($date, iformat => 'db');
849  
850 =cut
851  
852 sub check_date {
853 my ($date, %opts) = @_;
854  
855 $opts{iformat} ||= "norm";
856  
857 my $result;
858 my @d;
859  
860 eval {
861 @d = @{trdate($opts{iformat} => norm => $date)};
862 if (Date::Calc::check_date(@d[0 .. 2]) && Date::Calc::check_time(@d[3 .. 5])) {
863 $result = 1;
864 }
865 };
866  
867 if ($result) {
868 return 1;
869 } else {
870 return '';
871 }
872 }
873  
874 1;
875  
876 =head2 Extending trdate
877  
878 local $qbit::Date::TR_HS{'new_type'} = {
879 '>' => sub {my $dt_norm = shift; ...Convert $dt_norm to new_type code...},
880 '<' => sub {my $dt_new_type = shift; ...Convert $dt_new_type to norm code...};
881 };