Search code examples
javascriptdatedatetimedatepicker

Need to compare new date with datepicker


Im struggling with dates in javascript. Im going to compare some dates input but the user and the date the user input depends which list the information goes. My issue is comparing the system date and the date picker date. The system date shows the format of 'Tue Dec 22 2015 00:00:00 GMT+0000 (GMT)' date picker shows 22/12/2015. How can i change the system date to match the date picker format so i can compare dates? I want to do it without jQuery(i know date picker goes against this).

Here my code so far for the date which basically is just setting the time to 00:00:00.

var today = new Date();
today.setHours(0,0,0,0);

var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0,0,0,0);

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0,0,0,0);

console.log(today);


var dateTask = document.getElementById("date").value;

    console.log(dateTask);

Solution

  • You have to parse the user input into a Date object. 22/12/2015 is not a valid datestring for the Date constructor so you have to parse it yourself. You can do something like this:

    const [day, month, year] = document.getElementById("date").value.split('/');
    const dateTask = new Date(year, month - 1, day, 0, 0, 0, 0);
    

    Note: this code is very basic and needs an enhancement when you're parsing real user input.

    After that you can compare the dates like this:

    today.getTime() === dateTask.getTime()