1

I'm doing an app, and I encounter this problem, I thought comparing dates will be that easy but it's not. My condition inside if works well if the dates are of the same year, but if the value is like the value given below, it doesn't the result becomes true which should be false. So how do I properly compare this date format I have?

startDate.toLocaleDateString() has a value of 12/24/2016
endDate.toLocaleDateString() has a value of 01/03/2017

if(startDate.toLocaleDateString() > endDate.toLocaleDateString())
{
            //do this
}
else
{
     //do this
}
JC Borlagdan
  • 3,318
  • 5
  • 28
  • 51
  • Possible duplicate of [Compare two dates with JavaScript](http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Ryad Boubaker Jan 26 '17 at 08:48

1 Answers1

2

You could compare Date directly, because it uses EPOCH time, which is comparable.

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

if (startDate > endDate) {

It uses Date#valueOf

The valueOf() method returns the primitive value of a Date object.

and returns

The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392