Does anybody know of an easy way of taking a date (e.g. Today) and going back X days?
So, for example, if I want to calculate the date 5 days before today.
Does anybody know of an easy way of taking a date (e.g. Today) and going back X days?
So, for example, if I want to calculate the date 5 days before today.
I find a problem with the getDate()/setDate() method is that it too easily turns everything into milliseconds, and the syntax is sometimes hard for me to follow.
Instead I like to work off the fact that 1 day = 86,400,000 milliseconds.
So, for your particular question:
Works like a charm.
I use this method all the time for doing rolling 30/60/365 day calculations.
You can easily extrapolate this to create units of time for months, years, etc.
for me all the combinations worked fine with below code snipplet , the snippet is for Angular-2 implementation , if you need to add days , pass positive numberofDays , if you need to substract pass negative numberofDays
It goes something like this:
get moment.js. All the cool kids use it. It has more formatting options, etc. Where
Optional! Convert to JS Date obj for Angular binding.
Optional! Format
I like doing the maths in milliseconds. So use
Date.now()
and if you like it formatted
NOTE:
Date.now()
doesn't work in older browsers (eg IE8 I think). Polyfill here.UPDATE June 2015
@socketpair pointed out my sloppiness. As s/he says "Some day in year have 23 hours, and some 25 due to timezone rules".
To expand on that, the answer above will have daylightsaving inaccuracies in the case where you want to calculate the LOCAL day 5 days ago in a timezone with daylightsaving changes and you
Date.now()
gives you the current LOCAL now time, or.toString()
which returns the local date and therefore is incompatible with theDate.now()
base date in UTC.However, it works if you're doing your math all in UTC, eg
A. You want the UTC date 5 days ago from NOW (UTC)
B. You start with a UTC base date other than "now", using
Date.UTC()