Reputation: 23
I tried to compare two days and return an alert, if the startdate is higher than the enddate. I don't know why, but if I choose 19.04.2016 as the startdate and 01.05.2016 as the enddate, I receive the alert.
var main = function() {
var date1 = "";
var date2 = "";
$('h1').click(function() {
$('h1').remove();
})
$('#date-start').datepicker({
dateFormat: "dd.mm.yy",
minDate: new Date(),
onSelect: function(date) {
var startdate = $('#date-start').datepicker('getDate');
$('#date-end').datepicker('option','minDate',startdate);
}
})
$('#date-end').datepicker({
dateFormat: "dd.mm.yy"
})
$('#btn').click(function() {
date1 = $('#date-start').val();
date2 = $('#date-end').val();
if (date1 > date2) {
alert("Beginn muss vor dem Ende liegen");
$('#date-start').css("border-color","red");
$('#date-end').css("border-color","red");
}
if (date1 == "") {
alert("Bitte alle Felder ausfüllen");
$('#date-start').css("border-color","red");
$('#date-end').css("border-color","red");
}
document.getElementById("compare-date-text1").innerHTML = date1;
document.getElementById("compare-date-text2").innerHTML = date2;
})
}
$(document).ready(main)
Can you figure out why?
Thanks :)
Upvotes: 1
Views: 59
Reputation: 2343
You are comparing the date strings. Therefore, the string "19.04.2016" is greater than "01.05.2016". If you format the strings in the Datepicker ISO 8601 format "yy-mm-dd", then the strings should compare correctly. The better way is to call getDate
like the others have suggested.
Upvotes: 0
Reputation: 4222
When you set date1
and date2
you get string, not Date.
For get Date from datepicker you can use:
var date1 = new Date($('#date-start').datepicker('getDate'));
var date2 = new Date($('#date-end').datepicker('getDate'));
Then you can compare:
if (date1 > date2 ){.........}
Upvotes: 1
Reputation: 15154
to get the dates from the datepicker
you need to:-
date1 = $('#date-start').datepicker("getDate");
date2 = $('#date-end').datepicker("getDate");
you are getting them back as strings to compare instead of dates.
Upvotes: 0