JRS: In article <1x**********@hotpop.com>, dated Thu, 31 Mar 2005
03:47:43, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :
Christopher Benson-Manica <at***@nospam.cyberspace.org> writes:
If I try
d=new Date();
d.setMonth( 1 );
today, I'd really like to get some kind of an error rather than silent
failure.
Read the FAQ on dates; see sig.
Note that you can do d.setMonth(1, 1).
Sorry, that's not how Date works. You will have to create your own
method that checks whether the setting succeeded:
function setMonth(date, month) {
date.setMonth(month);
if (date.getMonth() != month) {
throw "invalid date for month";
// notice: date has already been updated.
}
}
That fails if the month being set is outside the range 0 to 11 and the
target month has sufficient days. I have preferred to get the initial
and final dates, and to take action if they differ.
function AlterMonth(DObj, By, Back) { // Back is boolean
with (DObj) { var Xd = getDate() ; setMonth(getMonth() + By)
if (Xd != getDate()) setDate(Number(Back)) // 0 or 1, as needed
} } // js-date0.htm
With that and yours, try going back 5 months from May 31st.
As you see, my code presumes that, rather than failure, either the last
day of the inadequate month or the first day of its successor should be
returned.
I expect it would be faster in UTC.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.