0

I am not a Perl programmer, but I am working on a program that uses the Date::Calc module like this

use Date::Calc ("Day_of_Year")
my $jday = Day_of_Year($yr[$n], $mon[$n}, $day[$n]);

I've been having issues with the module and I need to replace the above calculation of Julian day of year in my code.

Does anyone have any ideas? I don't have permissions to install modules so I need a base solution.

Borodin
  • 126,100
  • 9
  • 70
  • 144
user3367135
  • 131
  • 2
  • 12

2 Answers2

1
#!/usr/bin/perl
use strict;
use warnings;

use Time::Local qw[timegm];

# Computes the day of the year [1, 366] from the given year, month of the 
# year and day of the month.
# https://metacpan.org/pod/Time::Local#Year-Value-Interpretation
# 1 <= $m <= 12
# 1 <= $d <= 31 (day must be valid for the year and month)
sub ymd_to_doy {
    @_ == 3 or die q/Usage: ymd_to_doy(year, month, day)/;
    my ($y, $m, $d) = @_;
    my $t1 = timegm(0, 0, 0, $d, $m - 1, $y);
    my $t2 = timegm(0, 0, 0, 1, 0, $y);
    return 1 + int(($t1 - $t2) / 86_400);
}

use v5.10;
say ymd_to_doy(2015, 10, 11);
say ymd_to_doy(2015,  1,  1);
say ymd_to_doy(2015, 12, 31);
say ymd_to_doy(2012, 12, 31);

Output:

284
1
365
366
chansen
  • 2,446
  • 15
  • 20
0

See Date::Converter. If you can't install modules (even to your own home directory, really?), just copy the relevant code to yours.

choroba
  • 231,213
  • 25
  • 204
  • 289