Retang
Retang

Reputation: 1

Date comparision javascript

I am facing some problem in comparing dates in javascript.

I have dates in "1-Dec-2014" & "19-Nov-2014" format.

While I compared the dates like

var stDate='19-Nov-2014';
var endDate='1-Dec-2014';
if(stDate < endDate){
    console.log('Hi');
}else{
console.log('Bye');
}

In out put it shows me "Bye", but it should be "Hi".

What I observed it this comparison compares the date (initial argument) in respective dates.

I am very new to javascript . I am not getting any way to solve this .

Please help me.

Upvotes: 0

Views: 87

Answers (5)

Dhaval
Dhaval

Reputation: 2379

function ValidateDate() {
        var SDate = document.getElementById('<%=sdate.ClientID%>').value;
        var EDate = document.getElementById('<%=edate.ClientID%>').value;

        var sdate = new Date(stDate);

        var Edate = new Date(endDate);



        var alertReason1 = 'To Date must be greater than or equal to  From Date.'


        //var endDate = new Date(EDate);
        //var startDate = new Date(SDate);

        if (SDate != "" && EDate != "" && Edate > sdate ) {
            alert(alertReason1);

            return false;
        }

    }

Upvotes: 0

lepi
lepi

Reputation: 104

To handle dates correctly i'll quote Pavel Hodek


The best you can do is use the ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS

For example: new Date('2011-04-11')

or

new Date('2011-04-11T11:51:00')

For more Info: MDN | Date

Edit:

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00')

Note that the number of the month must be 1 less.

Important note:

The "ISO format" solution doesn't work 100% time. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). Calling toString returns the local time therefore depending on the users timezone in some cases new Date('2011-04-11') will give you 2011-04-10.

Chrome behaves the same as Internet Explorer 9 and Firefox behaves the same as Internet Explorer 10+.

Safe solution is passing string value with Z to be parsed as UTC value e.g. new Date('2011-04-11T10:20:30Z'). Best practice should always be to store dates as UTC and make computations as UTC. Only for presentation they should be presented as local time.


Once you have both dates (after parsing and/or using constructor) you can safely compare them.

Upvotes: 0

RobG
RobG

Reputation: 147523

As noted in other answers, you need to convert the strings to Date objects. The best way to do that is to parse the strings using a function like:

/* Return a Date object or NaN given a string in d, MMM y or dd-MMM-yyyy format
** e.g. 5 Dec, 2014
** Avoid conversion of two digit dates to 20th century
** Returns NaN if string is not a valid date
*/
function parseDMMMY(s) {
  var b = s.match(/\w+/g);
  var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
                jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
  if (b) {
    var d = new Date();
    d.setHours(0,0,0,0);
    d.setFullYear(b[2], months[b[1].toLowerCase()], b[0]);
  }
  return b && d.getFullYear() == b[2] && d.getDate() == b[0]? d : NaN;
}

This also treats dates like 1-1-19 as in year 19, rather than 1919 which may happen if the values are passed directly to the Date constructor rather than using the set* methods.

Now you can do:

var stDate  = parseDMMMY('19-Nov-2014');
var endDate = parseDMMMY('1-Dec-2014');

Upvotes: 0

Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27256

Just like @Arun P Johnny said, you are comparing Strings instead of actual dates. You need to convert you date to Date objects before comparing them. Check this out.

Upvotes: 0

Pramod Karandikar
Pramod Karandikar

Reputation: 5329

Currently you are only comparing two strings. You should compare the dates like this:

new Date(stDate) < new Date(endDate)

var stDate='19-Nov-2014';
var endDate='1-Dec-2014';
if(new Date(stDate) < new Date(endDate)){
      console.log('Hi');
}else{
      console.log('Bye');
}

Upvotes: 1

Related Questions