Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert date to day number of the year 1

Status
Not open for further replies.

pho01

Programmer
Mar 17, 2003
218
US
If I'm provided with a date, how do I convert it into day number of the year in Perl?

For example:
12/17/2004 ==>> 352

Thanks,



 
You can do this with the Day_of_Year function from the Date::Calc module, e.g.
Code:
#!perl
use strict;
use warnings;
use Date::Calc qw(Day_of_Year);

my $xdate = "12/17/2004";
my ($month, $day, $year) = split /\//, $xdate;
my $jdate = Day_of_Year($year, $month, $day);
print "$xdate = $jdate\n";
This is a nifty module. Check it out.

HTH

 
[tt]
BEGIN { print ordinal_day( 2004,12,17 ) }

function ordinal_day( y,m,d ,od )
{ od = int((306 * ((m<3) ? m+10 : m-2) - 2) / 10) - 30
od += (od < 306) ? 59 + leap_year( y ) : -306
return od + d
}

function leap_year(y)
{ return !(y%4 || y%400 && !(y%100) )
}
[/tt]
[tt]awk -f ord_day.awk [/tt] prints
[tt]
352[/tt]
 
Here's a version without cryptic equations:
[tt]
BEGIN { print ordinal_day( 2004,12,17 ) }

function ordinal_day( y,m,d ,mstr,p )
{ mstr = "1:0 2:31 3:59 4:90 5:120 6:151 " \
"7:181 8:212 9:243 a:273 b:304 c:334"
p = index( mstr, sprintf("%x:", m ) ) + 2
return d + substr(mstr, p) + (m>2 ? leap_year(y) : 0)
}

function leap_year(y)
{ return !(y%4 || y%400 && !(y%100) )
}
[/tt]
 
Simpler but slower:
Code:
function ordinal_day( y,m,d    ,marray )
{ split("0 31 59 90 120 151 181 212 243 273 304 334", marray)
  return d + marray[m] + (m>2 ? leap_year(y) : 0)
}
 
cntr
you're having a laugh ... i hope

yes it can be done cntr's way, but have a look at google
'julian date perl'

Want code, got $$$ ...
--Paul

cigless ...
 
The second link returned by Google was

It says

#**** julian date for. If your localtime() returns the year day *****
#**** return that, otherwise figure out the julian date. *****
#************************************************************************

Let's see if it can actually figure the ordinal day.
Change [tt]"if (defined($yday)) {"[/tt] to [tt]"if (0) {"[/tt] .

Add this at the bottom:
[tt]
# 2004/2/29
print &julianDate( 1078045200 ),",";
# 2004/3/1
print &julianDate( 1078131600 ),",";
# 2000/3/1
print &julianDate( 951901200 ),"\n";
[/tt]
It doesn't return the correct results for me.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top