How to add 30 minutes to a JavaScript Date object?

前端 未结 20 2968
醉酒成梦
醉酒成梦 2020-11-21 23:21

I\'d like to get a Date object which is 30 minutes later than another Date object. How do I do it with JavaScript?

20条回答
  •  情书的邮戳
    2020-11-22 00:08

    The easiest way to solve is the to recognize that in javascript dates are just numbers. It starts 0 or 'Wed Dec 31 1969 18:00:00 GMT-0600 (CST). Every 1 represents a millisecond. You can add or subtract milliseconds by getting the value and instantiating a new date using that value. You can manage it pretty easy with that mind.

    const minutesToAdjust = 10;
    const millisecondsPerMinute = 60000;
    const originalDate = new Date('11/20/2017 10:00 AM');
    const modifiedDate1 = new Date(originalDate.valueOf() - (minutesToAdjust * millisecondsPerMinute));
    const modifiedDate2 = new Date(originalDate.valueOf() + (minutesToAdjust * millisecondsPerMinute));
    
    console.log(originalDate); // Mon Nov 20 2017 10:00:00 GMT-0600 (CST)
    console.log(modifiedDate1); // Mon Nov 20 2017 09:50:00 GMT-0600 (CST)
    console.log(modifiedDate2); // Mon Nov 20 2017 10:10:00 GMT-0600 (CST)
    

提交回复
热议问题