Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare two string dates in javascript?

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?

like image 899
GLP Avatar asked Feb 08 '13 20:02

GLP


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.

How do I compare two date 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?

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.


1 Answers

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!"); } 
like image 197
Garry Avatar answered Oct 12 '22 22:10

Garry