Adding hours to JavaScript Date object?

前端 未结 16 1334
一生所求
一生所求 2020-11-22 09:00

It amazes me that JavaScript\'s Date object does not implement an add function of any kind.

I simply want a function that can do this:

var now = Date         


        
16条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 09:49

    SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.

    Here's how you do that:

    var milliseconds = 0;          //amount of time from current date/time
    var sec = 0;                   //(+): future
    var min = 0;                   //(-): past
    var hours = 2;
    var days = 0;
    
    var startDate = new Date();     //start date in local time (we'll use current time as an example)
    
    var time = startDate.getTime(); //convert to milliseconds since epoch
    
    //add time difference
    var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);
    
    var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now
    

    or do it in one line (where variable names are the same as above:
    var newDate = 
        new Date(startDate.getTime() + millisecond + 
            1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));
    

提交回复
热议问题