Add two dates times together in javascript

前端 未结 2 1389
無奈伤痛
無奈伤痛 2021-01-18 02:16

I am trying to add two dates:

date start Fri Apr 26 2013 16:08:03 GMT+0100 (Paris, Madrid)
+  
date periode Fri Apr 26 2013 00:10:00 GMT+0100 (Paris, Madrid         


        
2条回答
  •  一生所求
    2021-01-18 02:41

    If you want to add a time period to a date, you basically have to convert both of them into milliseconds.

    var date = new Date();
    var dateMillis = date.getTime();
    
    //JavaScript doesn't have a "time period" object, so I'm assuming you get it as a string
    var timePeriod = "00:15:00"; //I assume this is 15 minutes, so the format is HH:MM:SS
    
    var parts = timePeriod.split(/:/);
    var timePeriodMillis = (parseInt(parts[0], 10) * 60 * 60 * 1000) +
                           (parseInt(parts[1], 10) * 60 * 1000) + 
                           (parseInt(parts[2], 10) * 1000);
    
    var newDate = new Date();
    newDate.setTime(dateMillis + timePeriodMillis);
    
    console.log(date); //eg: Fri Apr 26 2013 08:52:50 GMT-0700 (MST)
    console.log(newDate); //eg: Fri Apr 26 2013 09:07:50 GMT-0700 (MST)
    

提交回复
热议问题