1

I am trying to compare the current date with two given dates in javascript.I am converting date in YYYY-mm-dd format and then comparing the dates. But I am observing strange thing. this is my code Java Script

function getyear()
{
    var year=document.getElementById('ddlyear').value;
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!

    var yyyy = today.getFullYear();
    if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = yyyy+'-'+mm+'-'+dd;
    document.getElementById('hdndate').value = today;
    var date1=document.getElementById('hdndate').value;
    alert(date1);

    var date2=new Date("2014-01-01");
    var dd = date2.getDate();
    var mm = date2.getMonth()+1; //January is 0!

    var yyyy = date2.getFullYear();
    if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var date2 = yyyy+'-'+mm+'-'+dd;

    alert(date2);
    var date3=new Date("2014-12-31");
    var dd = date3.getDate();
    var mm = date3.getMonth()+1; //January is 0!

    var yyyy = date3.getFullYear();
    if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var date3 = yyyy+'-'+mm+'-'+dd;

    alert(date3);

    if(year==1)
    {
        alert("January 2014-December 2014");

        if (date1 > date2 && date1 < date3 ){
         alert('Correct Date')
    }
    else{
        alert('Out Side range !!')
    }
    }
    else if(year==2)
    {
        alert("January 2015-December 2015");

    }
}

when i tried to alert date2 and date3 I am not getting the date which i have given The ouput for date2 and date3 is 2013-12-31 and 2014-12-30. I am not getting why this is coming up.Please help me in this regard. I am new to JS.

Firoz
  • 488
  • 2
  • 6
  • 21
  • possible duplicate of [How do I get the number of days between two dates in JavaScript?](http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript) – Paul Sweatte Feb 13 '14 at 00:31

1 Answers1

0

See the answer listed here regarding the incorrect parsing of dates according to the ISO standard, as I was unable to mark this as a duplicate. The reason for you issue is the same. If you check

date.toISOString();

You will see that the ISO format of the date is correct, but the Date object will by default show the parsed date under the current Time Zone.

Stack Overflow Post: javascript-date-parse

Community
  • 1
  • 1