bnghtz

week_of_the_year.pl

Jul 9th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.03 KB | None | 0 0
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4.  
  5. # it's the same as POSIX: "date +%V"
  6.  
  7. # Week of the Year
  8. # INPUT: firstDayOfTheWeek = 0:sun, 1:mon , undef:sun
  9. sub yweek(;$) {
  10.     my $fdw = shift // 0;
  11.     # current date => nth day of the year
  12.     #   0     1     2     3     4     5      6      [7]0   8
  13.     my (undef,undef,undef,undef,undef,undef, undef, $yday, undef) = localtime(time);
  14.     # (1st day of the year) was (which day of the week)?
  15.     #   0     1     2     3     4     5      [6]          7      8
  16.     my (undef,undef,undef,undef,undef,undef, $first_yday, undef, undef) = localtime(time - 24*60*60*$yday);
  17.     # if year starts w/ sunday and 1st day of the week is not sunday;
  18.     my $addFirstSunDelta = ($first_yday == 0 && $fdw != 0) ? 7 : 0;
  19.     my $weekNum = int(($yday + $first_yday - $fdw + $addFirstSunDelta) / 7)+1;
  20.  
  21.     return $weekNum;
  22. }
  23.  
  24. # testing:
  25. print yweek()   ."\n";
  26. print yweek(0)  ."\n";
  27. print yweek(1)  ."\n";
  28.  
  29. # special case: when a year starts with Sunday and the 1st day of the week is Monday;
Advertisement
Add Comment
Please, Sign In to add comment