Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select next and previous day with jQuery UI datepicker

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:

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/

like image 784
user715564 Avatar asked Jan 16 '14 17:01

user715564


People also ask

How can change date format in jQuery ui Datepicker?

inside the jQuery script code just paste the code. $( ". selector" ). datepicker({ dateFormat: 'yy-mm-dd' });

How to use jQuery ui datepicker?

The datepicker is tied to a standard form input field. Focus on the input (click, or use the tab key) to open an interactive calendar in a small overlay. Choose a date, click elsewhere on the page (blur the input), or hit the Esc key to close. If a date is chosen, feedback is shown as the input's value.


2 Answers

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

like image 88
adeneo Avatar answered Oct 12 '22 10:10

adeneo


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 -


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

like image 32
Jonathan Travers Avatar answered Oct 12 '22 12:10

Jonathan Travers