11

I am having a difficult time checking if one date is less than or equal to another.

Here is my code,

var bftStartDt = input1[0]; //This is a string with value "01-Jul-2007"
var bftEndDt = input1[4]; //This is a string with value "01-Jul-1942"

var strtDt = new Date(bftStartDt);
var endDt = new Date(bftEndDt);
var flag = 0; // false

if (endDt <= strtDt){
   flag = 1; // true
}

It never enters the if statement when it should ? What am I missing here.

Thanks

Beingnin
  • 2,288
  • 1
  • 21
  • 37
AJR
  • 569
  • 3
  • 12
  • 30

2 Answers2

13
var strtDt  = new Date("2007-07-01");
var endDt  = new Date("1942-07-01");
var flag = 0; // false

if (endDt <= strtDt){
   flag = 1; // true
   alert("true");
}

It works check out the plunker

CognitiveDesire
  • 774
  • 5
  • 20
0

The problem here is that 01-Jul-2007 is not a format supported by the Date object. Try doing 2007-01-07 instead. Then your program works as expected.

var bftStartDt = "01-07-2007"; //This is a string with value "01-Jul-2007"
var bftEndDt = "01-07-1942"; //This is a string with value "01-Jul-1942"

var strtDt = new Date(bftStartDt);
var endDt = new Date(bftEndDt);
var flag = 0; // false

if (endDt <= strtDt){
   flag = 1; // true
}

if(flag === 1) {
  console.log("It worked.");
}

According to MDN, the accepted formats are:

A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).

So you could also use the format Jul 01 2007. The full list of formats is in RFC 2822.

Community
  • 1
  • 1
Chris Middleton
  • 5,654
  • 5
  • 31
  • 68