Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to compare two dates, from strings, begin <= end

I get two strings formated like (Brazilian Format): "DD/MM/YYYY", I need to compare both. Since the first field is the begin and the last is the end,

My validation is begin <= end

Date.new(begin) is generating 'invalid date' even on ISO !

like image 758
Fabiano Soriani Avatar asked Feb 25 '10 17:02

Fabiano Soriani


People also ask

Can you compare two dates JavaScript?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.

Can you compare two dates as strings?

To compare two date strings:Pass the strings to the Date() constructor to create 2 Date objects. Compare the output from calling the getTime() method on the dates.

How can I compare two dates?

For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2. If date1 is smaller than date2, it prints Date 1 comes after Date 2.


1 Answers

Don't use Date.new. Use new Date(). Because of the format of your date string, I would recommend grabbing each field individually and passing them into the constructor:

var startYear = parseInt(document.getElementById('startYear'), 10);
var startMonth = parseInt(document.getElementById('startMonth'), 10) - 1; // as per Residuum's comment
var startDay = parseInt(document.getElementById('startDay'), 10);
var start = new Date(startYear, startMonth, startDay);

etc. If you're handed a date string, then you can use fuzzy lollipop's method to get each field from the string. I'm not sure if the Date constructor will accept unparsed strings for the individual fields, however.

The, once you have the two dates you'd like to compare, just compare their values in milliseconds since the epoch:

function isValid(start, end) {
    return start.getTime() < end.getTime();
}
like image 104
Matt Ball Avatar answered Sep 22 '22 17:09

Matt Ball