JRS: In article <HBeBd.108072$>, dated
Fri, 31 Dec 2004 15:53:11, seen in news:comp.lang.javascript, Mick White
<> posted :
>days=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
>
>// Find the Nth day(Three character string,
>// e.g "Thu", or use index [Sun=0, Sat=6])
>// of the month (full) of a given year (full)
>// To find the first Sunday of April 2004:
>// var spring = getNthDayInMonth(1,"Sun","April",2004)
>// or spring = getNthDayInMonth(1,0,"April",2004)
>// returns "4" (April 4th)
>function getNthDayInMonth(N,day,month,year){
>day=(getIndex(day,days)>-1)? getIndex(day,days):day;
>b=getMonthLength(month,year);
>d=7*N - 6 + (7+day-getFirstDayOfMonth(month,year))%7
>return d<b? d:"error";
>}
>See http://mickweb.com/javascript/dates/dateFunctions.html for
>supporting functions
For any given month, there is a value of N, 4 or 5, that should select
the very last day; e.g. 2005-01-31 is the Fifth Monday of this month.
But I would expect your b=getMonthLength(month,year) to be 31 for this
month, which the code seems to show as giving an error message for d=31.
Have I misunderstood?
If a Date Object is to be generated from the result, ISTM easier and
safer to confirm that getMonth() is as it should be. For speed, you
could use something like
return ( d < 29 || d <= getMonthLength ) ? d : 0
so that the expensive getMonthLength is only called in a few cases.
In practice, the month-length can only matter for N=5; and, as the
outside world has spotted this, the 5th X-day is rarely called for,
except when specified to mean the last X-day. The latter can easily be
obtained as the zeroth X-day of the following month.
Your function, as shown, pollutes the namespace by stomping on the
previous value of globals b & d.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.