I got the following property in an object, it is a string:
{end_date: '2017-04-05'}
I also have this :
const date = new Date();
How can i check if the end_date property is in the past. Something like
(obj.end_date < date ? true : false)
I got the following property in an object, it is a string:
{end_date: '2017-04-05'}
I also have this :
const date = new Date();
How can i check if the end_date property is in the past. Something like
(obj.end_date < date ? true : false)
If end_date
is in UTC, you can do this:
const endDate = new Date(obj.end_date + "Z");
const inThePast = endDate < date;
The Z
says UTC.
If it's local time (yes, it matters even with just a date), your best bet is to parse it and build it from parts:
const [year, month, day] = obj.end_date.split("-");
const endDate = new Date(+year, month - 1, +day); // Local time
const inThePast = endDate < date;
Without a timezone indicator on it, the spec says it should be parsed as UTC, hence creating it as above. However, this varied a bit in the specification, and implementations varied with it. ES5 said all strings without timezone indicators should be parsed as UTC, which was incompatible with ISO-8601; ES2015 said the opposite, which turned out to be incompatible with a lot of existing code; ES2016 and onward say UTC for date-only forms and local time for date/time forms). As of the end of 2018, my answer here says that with reasonably-modern browsers, the date-only form should reliably be parsed as UTC cross-browser. But if you want local, you have to do something else.
Non-standard, you could also rearrange it to the U.S. date format MM/DD/YYYY
(with /
, not -
) and every browser I've tried would parse it as local time. But if you're going to do that, you may as well use the constructor as shown above to specify the parts explicitly.
If you do not need to check timezone this should be enought:
const endDate = new Date(obj.end_date);
const isPast = endDate < date