简体   繁体   中英

How do I subtract minutes from a date in JavaScript?

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

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

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

It's just ticks

Ticks mean milliseconds since Jan 1st, 1970 at 0:0:0 UTC. The date constructor can take in a number as a single argument which is interpreted as ticks.

When working with number of milliseconds/seconds/hours/days/weeks (static quantities), you can do things like this

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

or

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

then let JavaScript display the date and worry about what day of the week it is or what day of the month and year etc. You can choose to localize it or internationalize it natively with Intl .

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.

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"

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

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.

Try as below:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM