Re: Perl Code: Julian day to mdy

Bill Moninger (moninger@fsl.noaa.gov)
Fri, 23 Feb 96 16:43:57 GMT


[Dr G M Weakley <glcj@argonet.co.uk> said...]
>   you offered to send the Perl code to arrive at mdy from the Julian
>day: Yes please.

Here is perl code for converting Julian day (day of year running from 1 to
366) to month, day, year.

I've checked this for both non-leap and leap years, and it works, but offer
no guarantees against pathological situations.

Please email me with any comments.

I guess I'll also post this to perl-announce.

Thanks for your interest.

-Bill
===============================snip
#!/usr/local/perl5/bin/perl
# subroutine gets julian day and [optional] year as arguments
# returns a list with (weekday, monthDay, month, year)
require "timelocal.pl"; 
sub jy2mdy {
    local ($i,$julday,$leap,$timeSecs);
    local ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
    ($julday,$year)=@_;
    
    #daytab holds number of days per month for regular and leap years
    local (@daytab) =(0,31,28,31,30,31,30,31,31,30,31,30,31,
                      0,31,29,31,30,31,30,31,31,30,31,30,31);
    local (@month)=(Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec);
    local (@day)=(Sun,Mon,Tue,Wed,Thu,Fri,Sat);


    #see if year was defined
    if($year == 0) {
        $timeSecs=time();
        ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
            = gmtime($timeSecs);
    }

    #see if the year is a leap year 
    $leap = ($year%4 == 0 && $year%100 != 0) || $year%400 == 0;
    for($i=1,$mday = $julday ; $mday  > $daytab[$i + 13 * $leap]  ; $i++) {
        $mday -= $daytab[$i + 13 * $leap];
    }
    $mon=$i-1;

    $timeSecs=timegm(0,0,0,$mday,$mon,$year);
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
        = gmtime($timeSecs);

    ($day[$wday],$mday,$month[$mon],$year);
}
================= snip

-------------------------
William R. Moninger, Nat'l Oceanic & Atmospheric Administration (NOAA)
Forecast Systems Laboratory, R/E/FS1
325 Broadway;     Boulder, CO 80303; USA
moninger@fsl.noaa.gov; Voice: 303-497-6435;  Fax: 303-497-3329
URL: http://www.fsl.noaa.gov/frd-bin/bill.homepage.cgi