How to add 30 minutes to a JavaScript Date object?

前端 未结 20 2986
醉酒成梦
醉酒成梦 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:10

    I know that the topic is way too old. But I am pretty sure that there are some developpers who still need this, so I made this simple script for you. I hope you enjoy it!

    Hello back, It's 2020 and I've added some modification hope it will help a lot better now!

    function strtotime(date, addTime){
      let generatedTime=date.getTime();
      if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds 
      if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes 
      if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours 
      return new Date(generatedTime);
    }
    
    Date.prototype.strtotime = function(addTime){
      return strtotime(new Date(), addTime); 
    }
    
    let futureDate = new Date().strtotime({
        hours: 16, //Adding one hour
        minutes: 45, //Adding fourty five minutes
        seconds: 0 //Adding 0 seconds return to not adding any second so  we can remove it.
    });

提交回复
热议问题