How do I subtract minutes from a date in JavaScript?

Javascript

Javascript Problem Overview


How can I translate this pseudo code into working JS [don't worry about where the end date comes from except that it's a valid JavaScript date].

var myEndDateTime = somedate;  //somedate is a valid JS date  
var durationInMinutes = 100; //this can be any number of minutes from 1-7200 (5 days)

//this is the calculation I don't know how to do
var myStartDate = somedate - durationInMinutes;

alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());

Javascript Solutions


Solution 1 - Javascript

Once you know this:

  • You can create a Date by calling the constructor with milliseconds since Jan 1, 1970.
  • The valueOf() a Date 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);

Solution 2 - Javascript

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);

Solution 3 - Javascript

It's just ticks...

when working with milliseconds/seconds/hours/days/weeks as those are statically known quantities.

const aMinuteAgo = new Date( Date.now() - 1000 * 60 );

or

const aMinuteLess = new Date( someDate.getTime() - 1000 * 60 );

...then let JavaScript display the data and worry about what month and year it is and how to internationalize it.

I recommend using luxon for JavaScript related projects when you are doing anything more complicated than the above mentioned that requires arbitrary timezones or leap years or days of the month etc.

Solution 4 - Javascript

moment.js has some really nice convenience methods to manipulate date objects

The .subtract method, allows you to subtract a certain amount of time units from a date, by providing the amount and a timeunit string.

var now = new Date();
// Sun Jan 22 2017 17:12:18 GMT+0200 ...
var olderDate = moment(now).subtract(3, 'minutes').toDate();
// Sun Jan 22 2017 17:09:18 GMT+0200 ...

Luxon also has an API to manipulate it's own DateTime object

var dt = DateTime.now(); 
// "1982-05-25T00:00:00.000Z"
dt.minus({ minutes: 3 });
dt.toISO();              
// "1982-05-24T23:57:00.000Z"

Solution 5 - Javascript

This is what I found:

//First, start with a particular time
var date = new Date();

//Add two hours
var dd = date.setHours(date.getHours() + 2);

//Go back 3 days
var dd = date.setDate(date.getDate() - 3);

//One minute ago...
var dd = date.setMinutes(date.getMinutes() - 1);

//Display the date:
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var date = new Date(dd);
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
var displayDate = monthNames[monthIndex] + ' ' + day + ', ' + year;
alert('Date is now: ' + displayDate);

Sources:

http://www.javascriptcookbook.com/article/Perform-date-manipulations-based-on-adding-or-subtracting-time/

https://stackoverflow.com/a/12798270/1873386

Solution 6 - Javascript

var date=new Date();

//here I am using "-30" to subtract 30 minutes from the current time.
var minute=date.setMinutes(date.getMinutes()-30); 

console.log(minute) //it will print the time and date according to the above condition in Unix-timestamp format.

you can convert Unix timestamp into conventional time by using new Date().for example

var extract=new Date(minute)
console.log(minute)//this will print the time in the readable format.

Solution 7 - Javascript

Try as below:

var dt = new Date();
dt.setMinutes( dt.getMinutes() - 20 );
console.log('#####',dt);

Solution 8 - Javascript

Extend Date class with this function

// Add (or substract if value is negative) the value, expresed in timeUnit
// to the date and return the new date.
Date.dateAdd = function(currentDate, value, timeUnit) {

    timeUnit = timeUnit.toLowerCase();
    var multiplyBy = { w:604800000,
                     d:86400000,
                     h:3600000,
                     m:60000,
                     s:1000 };
    var updatedDate = new Date(currentDate.getTime() + multiplyBy[timeUnit] * value);

    return updatedDate;
};

So you can add or substract a number of minutes, seconds, hours, days... to any date.

add_10_minutes_to_current_date = Date.dateAdd( Date(), 10, "m");
subs_1_hour_to_a_date = Date.dateAdd( date_value, -1, "h");

Solution 9 - Javascript

This is what I did: see on Codepen

var somedate = 1473888180593;
var myStartDate;
//var myStartDate = somedate - durationInMuntes;

myStartDate = new Date(dateAfterSubtracted('minutes', 100));

alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());

function dateAfterSubtracted(range, amount){
    var now = new Date();
    if(range === 'years'){
        return now.setDate(now.getYear() - amount);
    }
    if(range === 'months'){
        return now.setDate(now.getMonth() - amount);
    }
    if(range === 'days'){
        return now.setDate(now.getDate() - amount);
    }
    if(range === 'hours'){
        return now.setDate(now.getHours() - amount);
    }
    if(range === 'minutes'){
        return now.setDate(now.getMinutes() - amount);
    }
    else {
        return null;
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbrendanView Question on Stackoverflow
Solution 1 - JavascriptDaniel LeCheminantView Answer on Stackoverflow
Solution 2 - JavascriptMiquelView Answer on Stackoverflow
Solution 3 - JavascriptKing FridayView Answer on Stackoverflow
Solution 4 - JavascriptsvarogView Answer on Stackoverflow
Solution 5 - JavascriptcrashwapView Answer on Stackoverflow
Solution 6 - JavascriptRajesh Vinay KumarView Answer on Stackoverflow
Solution 7 - JavascriptJitendraView Answer on Stackoverflow
Solution 8 - JavascriptGonzalo CaoView Answer on Stackoverflow
Solution 9 - JavascriptRonnie RoystonView Answer on Stackoverflow