Click here to Skip to main content
16,016,760 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hu
i want to compare two dates in java script.

JavaScript
if uk
var dt=new Date("MM/dd/yyyy");
var dt2=new Date("MM/dd/yyyy");

if browser lang french
var dt=new Date("dd/mm/yyyy");
var dt2=new Date("dd/mm/yyyy");

if spanish....etc

How can i compare two dates independent of watsoever client may use culture in his browser.
Posted
Updated 3-Dec-11 8:22am
v2

1 solution

I would personally ensure your date entry for manual entries is clear in the format expected, I prefer DD-MMM-YYYY, removes all ambiguity. Also, if the date is not recognised handle this error (the code below will write out any "invalid date").

The first thing to do, is parse the dates in a date object.

Then simply perform an equality test of the valueOf the date object (according to the javascript docs, valueOf output is the same as toString).

XML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
</head>
<body>
    Date Input 1;<br />
    <input id="Text1" type="text" /><br />
    Date Input 2;<br />
    <input id="Text2" type="text" /><br />
    <input id="Button1" type="button" value="Compare Dates" onclick="compareDates()" />
    
<div id="output">Enter the dates and hit the button.</div>
<script type="text/javascript">

    function compareDates() {
        var d1 = new Date(Date.parse(Text1.value));
        var d2 = new Date(Date.parse(Text2.value));

        output.innerHTML = "D1 value is: " + d1.toUTCString() + "<br />" + "D2 value is: " + d2.toUTCString();

        alert("Are the dates the same; " + (d1.valueOf() == d2.valueOf()));

    }

</script>

</body>
</html>
 
Share this answer
 
v3
Comments
Monjurul Habib 4-Dec-11 6:17am    
my 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900