Domanda

I am tring to compare two date with javascript.Actually my goal getting warning message if first date is graeter than second date but javascript does not work properly.While i am debugging on firefox cursor going to else block, even if happens condition.Meanwhile, similar javascript code works properly that on jsfiddle.

http://jsfiddle.net/Mjora/ZNaMW/

Javascript code

$("#btn").click(function(){
    var firstDate = $('#firstDate').val();
    var lastDate = $('#lastDate').val();

    if (firstDate > lastDate) {
        alert("First date can not be greater than Last date!!");
    }
    else{...} 
});

Also i tried code like these;

   $("#btn").click(function(){
        var firstDate = $('#firstDate').val();
        var lastDate = $('#lastDate').val();

        if (new Date(firstDate) > new Date(lastDate)) {
            alert("First date can not be greater than Last date!!");
        }
        else{...} 
    });

 /********/

var fDate="10.10.2020";
var lDate="10.10.2010";

var fDateSpl= fDate.Split(".");
var lDateSpl= lDate.Split(".");

var newFDate = new Date(fDateSpl[2], fDateSpl[1], fDateSpl[0]);
var newLDate = new Date(lDateSpl[2], lDateSpl[1], lDateSpl[0]);


if (newFDate > newLDate) {
    alert("First date can not be greater than Last date!!");
}
else{...} 

Html

<input type="text" id="firstDate"/>
    <br/>
<input type="text" id="lastDate"/>
    <br/>
<input type="button" value="Send" id="btn"/>
È stato utile?

Soluzione

Use Date.parse(firstDate) > Date.parse(lastDate)

$("#btn").click(function(){
    var firstDate = $('#firstDate').val();
    var lastDate = $('#lastDate').val();
    if (Date.parse(firstDate) > Date.parse(lastDate)) {
        alert("First date can not be greater than Last date!!");
    } 
});

Fiddle Link

Altri suggerimenti

Your first attempt if (firstDate > lastDate) { fails because it is a string comparrison, not a date comparison.

And your other attempt failed because of a typo

var fDateSpl= fDate.Split(".");
var lDateSpl= lDate.Split(".");

should be

var fDateSpl= fDate.split(".");
var lDateSpl= lDate.split(".");

change that and you will have an alert appear

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top