javascript 使用 jQuery UI 日期选择器选择下一天和前一天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21168540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:16:35  来源:igfitidea点击:

Select next and previous day with jQuery UI datepicker

javascriptjqueryjquery-uidatepicker

提问by user715564

I am using the jQuery UI datepicker and I have a button that changes the selected date forward by one day and a button that changes the selected date backwards by one day. Right now, my "previous day" button works just fine. If click my previous button several times and then click my "next day" button, it only increments the date once. For example, if the datepicker is set to 1/10/2014 and I click the "next day" button, it will be updated to 1/11/2014 but if I click it again, nothing will happen. If I click the "next day" button without first clicking the "previous day" button it will work just fine. Here is my jQuery:

我正在使用 jQuery UI 日期选择器,我有一个按钮可以将所选日期向前更改一天,还有一个按钮可以将所选日期向后更改一天。现在,我的“前一天”按钮工作正常。如果多次单击我的上一个按钮,然后单击我的“第二天”按钮,它只会增加一次日期。例如,如果日期选择器设置为 1/10/2014 并且我单击“第二天”按钮,它将更新为 1/11/2014,但如果我再次单击它,则不会发生任何事情。如果我单击“第二天”按钮而不先单击“前一天”按钮,它将正常工作。这是我的 jQuery:

var currentDay = new Date();
var nextDay = new Date();
var previousDay = new Date();

$('.next-day').each(function() {
    $(this).on("click", function () {

        if (previousDay < currentDay) {
            nextDay.setDate(previousDay.getDate() + 1);
        } else {
            nextDay.setDate(nextDay.getDate() + 1);
        }

        $('#to').datepicker("setDate", nextDay);
        $('#from').datepicker("setDate", nextDay);
    });
});

Edit: Here is a jsFiddle http://jsfiddle.net/p2T2g/

编辑:这是一个 jsFiddle http://jsfiddle.net/p2T2g/

回答by adeneo

It's not that hard, something like

没那么难,有点像

$('.next-day').on("click", function () {
    var date = $('#picker').datepicker('getDate');
    date.setTime(date.getTime() + (1000*60*60*24))
    $('#picker').datepicker("setDate", date);
});

$('.prev-day').on("click", function () {
    var date = $('#picker').datepicker('getDate');
    date.setTime(date.getTime() - (1000*60*60*24))
    $('#picker').datepicker("setDate", date);
});

FIDDLE

小提琴

回答by Jonathan Travers

Above solution isn't quite right when you factor in Daylight Savings - E.g. country like UK you'll be 1 hour short, better to do below for 1 day increment -

当您考虑夏令时,上述解决方案不太正确-例如,像英国这样的国家您将缩短 1 小时,最好在下面以 1 天为增量进行-

    $('.next-day').on("click", function () {
        var date = $('#picker').datepicker('getDate');
        date.setDate(date.getDate() + 1)
        $('#picker').datepicker("setDate", date);
    });