1

I have two dates in DD/MM/YYYY HH:MM:SS format ,i want to compare two dates and throw an

alert .

I tried the below code,but it is not working.

startdate = "14/12/2014  19:00:00";
enddate = "21/01/2015  19:00:00";

if(new Date(startdate) > new Date(enddate))
{
    alert("End date cannot be less than start date");

}
potashin
  • 44,205
  • 11
  • 83
  • 107
mark rammmy
  • 1,478
  • 5
  • 27
  • 61

1 Answers1

5

You can create a Date using the following constructors:

new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);

You have used the third of them, where the dateString is a

String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

The string you have provided hasn't the correct format. Hence the corresponding date objects haven't been created.

I would prefer using the last constructor, since I wouldn't have to format correspondingly the strings.

var startDate = new Date(2014,12,14,19,0,0);
var endDate = new Date(2015,1,21,19,0,0);

I swapped the startDate with the endDate, in order we see the alert.

var endDate = new Date(2014,12,14,19,0,0);
var startDate = new Date(2015,1,21,19,0,0);

if(startDate > endDate)
{
    alert("End date cannot be less than start date");
}
Christos
  • 53,228
  • 8
  • 76
  • 108