How do I subtract minutes from a date in JavaScript?
Once you know this:
- You can create a
Date
by calling the constructor with milliseconds since Jan 1, 1970. - The
valueOf()
aDate
is the number of milliseconds since Jan 1, 1970 - There are
60,000
milliseconds in a minute :-]
In the code below, a new Date
is created by subtracting the appropriate number of milliseconds from myEndDateTime
:
var MS_PER_MINUTE = 60000;
var myStartDate = new Date(myEndDateTime - durationInMinutes * MS_PER_MINUTE);
You can also use get and set minutes to achieve it:
var endDate = somedate;
var startdate = new Date(endDate);
var durationInMinutes = 20;
startdate.setMinutes(endDate.getMinutes() - durationInMinutes);
Everything is just ticks, no need to memorize methods...
var aMinuteAgo = new Date( Date.now() - 1000 * 60 );
or
var aMinuteLess = new Date( someDate.getTime() - 1000 * 60 );
update
After working with momentjs, I have to say this is an amazing library you should check out. It is true that ticks work in many cases making your code very tiny and you should try to make your code as small as possible for what you need to do. But for anything complicated, use momentjs.