I have two string dates in the format of m/d/yyyy. For example, “11/1/2012”, “1/2/2013”. I am writing a function in JavaScript to compare two string dates. The signature of my function is bool isLater(string1, string2),
if the date passed by string1 is later than the date passed by string2, it will return true, otherwise false. So, isLater(“1/2/2013”, “11/1/2012”) should return true. How do I write a JavaScript function for this?
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.
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.
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
var d1 = Date.parse("2012-11-01"); var d2 = Date.parse("2012-11-04"); if (d1 < d2) { alert ("Error!"); }
Demo Jsfiddle
Recently found out from a comment you can directly compare strings like below
if ("2012-11-01" < "2012-11-04") { alert ("Error!"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With