How do I subtract minutes from a date in javascript?

后端 未结 9 2177
囚心锁ツ
囚心锁ツ 2020-11-29 03:25

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 myEndD         


        
9条回答
  •  醉话见心
    2020-11-29 03:34

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

提交回复
热议问题