首页 文章

在给定日期添加两个小时

提问于
浏览
1

以下代码用于获取日期值,然后向其添加两个小时 . 我真的很想知道如何在早上08:30到晚上18:30之间添加两个小时的条件,并跳过这两天(周六,周日) .

例如:如果给定的日期是星期二的17:30,那么它将遵循规则(17:30(星期二)2 = 09:30(星期三 - 第二天),如果给定的日期是17:00(星期五),如果我们跳过周末09:00(星期一 - 跳过周末)等等...

var now = new Date(Date.parse($(".x-form-hidden.x-form-field :eq(0)").val()));

now.setHours(now.getHours() + 2);

var dayVar = "";

if (now.getDate() < 10) {
    dayVar = 0 + "" + now.getDate()
} else {
    dayVar = now.getDate();
}

var dateString = 
    now.getFullYear() + "-" + 
    (now.getMonth() + 1) + "-" + 
    dayVar + " " + 
    now.getHours() + ":" + now.getMinutes() + ":0" + now.getSeconds();

$(".x-form-hidden.x-form-field :eq(1)").attr('value', dateString);

1 回答

  • 1
    function addTwoHours(date) {
        //date to decimal
        var day = date.getDay() - 1;
        var hour = date.getHours() - 8;
        var decimal = day * 10 + hour;
    
        //add two hours
        decimal += 2;
    
        //decimal to date
        var newDay = Math.floor(decimal / 10);
        var nextDay = newDay - day == 1;
        var weekEnd = newDay % 5 == 0;
        var newHour = (decimal % 10) + 8;
        var newDate = new Date(date.getTime() + (nextDay?24:0) * (weekEnd?3:1) * 60 * 60 * 1000);
        newDate.setHours(newHour);
        return  newDate;
    }
    

    您的时间范围表示每周5天,每天10小时,因此可以轻松映射到50小时的连续区域 . 考虑到然后单位和数十给出了转变 .

    以下示例获取2月1日星期五17:15的日期,该日期将于2月4日星期一9:15返回 . addTwoHours(new Date(2013, 1, 1, 17, 15));

相关问题