In comp.lang.javascript message <cd5edca8-7cd4-422a-9d71-3c6f35f1af24@k3
g2000prl.googlegroups.com>, Tue, 3 May 2011 14:14:28, Erich93063
What is the proper syntax to see if a given date falls within 3 years
from todays date? I need it to actually do three years not just take
the year of todays date and subtract 3 which may not actually be three
full years ago. In other words if we are mid way through this year. I
need to go back mid way through the year three years ago.
Basically I have some records that have dates attached to them and i
only want to display them if they are between today and exactly three
years ago.
Today being 2011-05-04, you mean files from after the end of 2008-05-03,
or files from after the end of 2008-05-04, or files from after the
current time on 2008-05-04. Or possibly something else. You also need
to consider what to do about leap years; when exactly was three years
before 2012-02-29?
You need to be aware of the possibility that one date is in Summer Time
and the other is not (if you are American and wanted five years ago, you
would also have to consider whether the change in DST rules effective
2007-03-01 [at presumably 00:00:00 local time] might matter).
And you should consider what to do if your business operates in more
than one time zone or in places with different Summer Time Rules -
especially Tel Aviv. Perhaps UTC should be used.
To get the date three years ago, letting the effect of those
considerations be what it might, you only need
D = new Date()
D.setFullYear(D.getFullYear()-3)
// D.setUTCFullYear(D.getUTCFullYear()-3)
You can compare date objects such as D with D1>D2 etc.
You can remove the time from a local date with D.setHours(0,0,0,0).
But, if your midway example be taken literally, you need (if either year
is Leap) to take the fraction of the way through the current year,
including the effects of February 29 and Summer Time, and apply that
fraction to the year three before - which will be in general at a
different time of day and often a different day, or date, of the year.
Some of those considerations apply to the upper end of the allowable
range; remember that clocks go BACK in autumn, so an hour is repeated.
See sig below, and its js-index.htm & js-dates.htm.