-1

I have a date in the format as "16-Jun-2015" and I need to compare it to today's date to see it is not larger.

Since my input date is a string I first converted to a date object:

new Date("16-Jun-2015");

Then I took this to compare to today's date:

if(date.compare(new Date("16-Jun-2015"), new Date()) > 0){
   //Do stuff if input is larger than today's date
}

The new Date("16-Jun-2015") returns the value 'Invalid date.' How can I compare these dates? I also cannot use any third-party Date libraries, as I do not own the entire codebase I'm working with.

The duplicate question message is incorrect as that question only displays parsing, but not comparing.

Danny Delott
  • 6,756
  • 3
  • 33
  • 57
user2924127
  • 6,034
  • 16
  • 78
  • 136

2 Answers2

1

Take a look at the documentation surrounding the Date object in JavaScript.

In essence, your usage of the new Date('16-Jun-2015') is invalid as the Date constructor expects a very specific input format.

This means you'll need to convert your date format ("16-Jun-2015") into a compatible format, either ISO-8601 or RFC2822.

Converting your date's format to one of these standards is unavoidable. This process can be made easier with third-party libraries, like Moment.js.

Community
  • 1
  • 1
Danny Delott
  • 6,756
  • 3
  • 33
  • 57
1

Because the format you are providing is not standardized, it's not guaranteed to be supported by the Date constructor.

There are multiple approaches to solving this problem, but the easiest one is to use a library such as moment.js, which has its own parsing functions that you can control with format specifiers.

For example:

if (moment("16-Jun-2015","D-MMM-YYYY").isAfter())
    ...

Note that in this example, the isAfter function uses the current date and time because it was not passed any parameters.

However, since you said you couldn't use a library, consider a simple parsing function of your own, such as:

var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

function parseDate(s){
    var parts = s.split("-");
    var d = parts[0];
    var m = months.indexOf(parts[1]);
    var y = parts[2];
    return new Date(y, m, d);
}

Which you can simply call like so:

if (parseDate("16-Jun-2015") > new Date())
    ...
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575