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 :)
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 ){.........}
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.
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.
Related
I got this code (off GitHub) It does exactly what I want except the months produced are a month ahead of the months in the JavaScript code. The months in this code are 02 (February) but the months produced on screen are 03 (March). What am I not seeing here? Is it the way the dates are written?
<script>
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate,1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2021,02,22), new Date(2021,02,27));
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
</script>
As Timespider pointed out, getDates function is OK. You mus be careful when creating a new Date value, since months go from 0 to 11 in the Date constructor function:
// Usage
var fromFeb22 = new Date(2021,1,22);
var toFeb27 = new Date(2021,1,27);
var dates = getDates(fromFeb22 , toFeb27 );
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
UPDATE: Using with jQuery's DatePicker
The jQuery's DatePicker widget has a getDate method which returns a Date object that you can use directly in your function (no need to use new Date()):
// Usage
var fromDate = $("#fromDate").datepicker("getDate");
var toDate = $("#toDate").datepicker("getDate");
var dates = getDates(fromDate, toDate);
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
Using with standard date input <input type="date"/>
The standard date input returns the date as a string formatted like "yyyy-MM-dd", but it is easy to parse it into a Date object:
// Usage
var fromDate = new Date(document.querySelector("#fromDate").value);
var toDate = new Date(document.querySelector("#toDate").value);
var dates = getDates(fromDate, toDate);
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
I am using the Foundation-Datepicker and I have it so the user can only pick a start date that is after current date (i.e. all other values are unable to be selected).
I would like the end date to work in the same manner where the user can only pick a date after the start date.
I have the dates (days) working, i.e. user cannot select 1 January 2016 as the end date if the start date is 3 January 2016.
My first problem is due to the fact that I cannot have the start date to be the same as the end date, and secondly because I am also using time I would like it to disable all selections following the start date/time for end date/time popup.
i.e. user can select 1 January 2016, 13:00 as start and 1 January, 14:00 as end.
My code is the following:
// Get Date of today
var newDate = new Date();
// Prase newDate
var now = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate(), 0, 0, 0, 0);
// Initialize datepicker with restricted date
var startDate = $('.has-datepicker').fdatepicker({
format: "dd/mm/yyyy - hh:ii",
pickTime: true,
onRender: function (date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (e) {
if (e.date.valueOf() > endDate.date.valueOf()) {
var newDate = new Date(e.date);
newDate.setDate(newDate.getDate() + 1);
endDate.update(newDate);
}
}).data('datepicker');
var endDate = $('.has-datepicker2').fdatepicker({
format: "dd/mm/yyyy - hh:ii",
pickTime: true,
onRender: function (date) {
return date.valueOf() <= startDate.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(e) {
}).data('datepicker');
// implementation of disabled form fields
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#dpd1').fdatepicker({
onRender: function (date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 1);
checkout.update(newDate);
}
checkin.hide();
$('#dpd2')[0].focus();
}).data('datepicker');
var checkout = $('#dpd2').fdatepicker({
onRender: function (date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
checkout.hide();
}).data('datepicker');
try like this.. better go through the site and docs fully
I'm using JSON to store data and using date range picker as the follows code.
$(function() {
$("#datepicker").datepicker({
beforeShowDay: function(date) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
},
onSelect: function(dateText, inst) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
if (!date1 || date2) {
$("#input1").val(dateText);
$("#input2").val("");
$(this).datepicker("option", "minDate", dateText);
} else {
$("#input2").val(dateText);
$(this).datepicker("option", "minDate", null);
}
//$("#dateoutput").html("Chosen date is <b>" + date1 + "</b> - <b>" + dateText + "</b>");
}
});
});
How can i bind data according to selected date range.
enter code here
I'm not entirely sure what it was you wanted to do, but I've made a JSFiddle from what I understood.
To test, do this:
1) I have saved an initial date as a JSON string, so you can click on "Load JSON Date" and it will parse the JSON string and store the values in the 2 input fields.
2) You can then select another date range, and click "Store JSON Data" and it will stringify the data.
3) Change the date
4) click "Load JSON Data" and it will reset the fields back to the data you stored.
http://jsfiddle.net/1xqbgshm/4/
The code does the following:
$("#store").click(function () {
var date1 = $("#input1").val();
var date2 = $("#input2").val();
var dateObject = {
"fromDate": date1,
"toDate": date2
};
jsonString = JSON.stringify(dateObject);
alert(jsonString);
});
$("#load").click(function () {
var javascriptObject = $.parseJSON(jsonString);
$("#input1").val(javascriptObject.fromDate);
$("#input2").val(javascriptObject.toDate);
});
Does this help?
I have two Jquery date pickers, in which a range of dates can be selected.
I have implemented certain restrictions like, the date of textbox2 should be always greater than textbox1. In addition I have disabled certain dates.
What I need is, if a user selects from date, and then selects to date, if there exist a disabled date in between, then the user should not be able to select that range.
For example:
I have disabled the dates: "31-5-2014", "1-6-2014", "2-6-2014"
If user selects date1 as 29-5-2014, and tries to select 4-6-2014 as the second date, then he should not be able to do that as disabled dates are in betweeb. The max value for date2 must be 30-5-2014
Adding the fiddle
I added a function "validateDateRange" to your code to illustrate the logic required to complete this task. Please note that the intention of the function I added is to simply pop up an alert if the condition you described occurs. From here you should be able to do whatever you like. Let us know if you have more questions or were looking for something else.
Here are my updates
function validateDateRange() {
var txtStartDate = $("#start_date");
var txtEndDate = $("#end_date");
var startDate;
var endDate;
var tempDate;
if (txtStartDate.val() == "")
return false;
if (txtEndDate.val() == "")
return false;
startDate = new Date(txtStartDate.val());
endDate = new Date(txtEndDate.val());
for (i = 0; i < unavailableDates.length; i++) {
var temp = unavailableDates[i].split("-");
tempDate = new Date(temp[2], temp[1]-1, temp[0]);
if (startDate < tempDate && endDate > tempDate) {
alert("Invalid Date Range");
return false;
}
}
}
Provided that The jQuery UI Datepicker doesn't support such functionality, manual way is the way ahead.
You can use onSelect option of date picker in start_date date Picker to achieve this functionality.
$('#start_date').datepicker(
{
beforeShow: customRangeStart,
beforeShowDay: unavailable,
minDate: 0,
dateFormat: "yy-mm-dd",
changeYear: true,
onSelect: function() {
//Do validation functionality here
triggerOnStartSelect();
}
});
And write down the validation functionality for setting the new maxDate of end_date date picker as :
//Trigger upon change event of either start or end date
function triggerOnStartSelect(){
var startDate = new Date($("#start_date").datepicker("getDate"));
var endDate = new Date($("#end_date").datepicker("getDate"));
//if required you could reset all of the default setting here //
//And can also validate the date objects
//Holds to be set maxdate of end_date datepicker
var tempEndDate= null ;
//unavailableDateObjects : Array of date objects listed as disabled
$.each(unavailableDateObjects, function(i, disabledRangeDate) {
if (startDate < disabledRangeDate) {
tempEndDate=new Date(disabledRangeDate);
//subtracts one day from the nearest disabled range date
tempEndDate.setDate(tempEndDate.getDate() - 1);
return false;
}
});
//Sets maxDate to the closest disabled date range or null . if null denotes no maxdate.
$( "#end_date" ).datepicker( "option", "maxDate", tempEndDate);
}
And you could obtain the date objects array from your string array list
var unavailableDates = ["31-5-2014", "1-6-2014", "2-6-2014", "3-6-2014"];
as (Or you could directly define date array object resembling the unavailableDates array ):
//Convert String Date List to Date object List
function convertDisabledFieldToDateObject(diabledList) {
var dateList = [];
$.each(diabledList, function (i, singleDate) {
var parsedDate = $.datepicker.parseDate("dd-mm-yy",singleDate);
dateList.push(parsedDate);
});
//Sort date if the diabled date sets are in jumbled order
dateList.sort(function(date1, date2){
return date1 - date2;
});
return dateList;
}
Which would be called after initialization of date string array.
Check out this Demo Fiddle
On course of solving this question, i found one interesting question that could be used for solving this problem(could be) :
JQuery Datepicker find next disabled date
var StartDate = $("#start_date").val();
var EndDates = $("#end_date").val();
var selectedDate = $("#selected_date").val();
//-- Start Date Convert in YMD
var Sdate = StartDate.split("-");
var Syear= Sdate[2];
var Smonth= Sdate[1];
var Sday= Sdate[0];
var SYMDDate = Syear + '-' + Smonth + '-' + Sday;
var newdate= new Date(SYMDDate);
var StartDateStrToTime=newdate.getTime();
//-- End Date Convert in YMD
var Edate = EndDates.split("-");
var Eyear= Edate[2];
var Emonth= Edate[1];
var Eday= Edate[0];
var EYMDDate = Eyear + '-' + Emonth + '-' + Eday;
var newdates= new Date(EYMDDate);
var EndDateStrToTime=newdates.getTime();
//-- Selected Date Convert in YMD
var Cdate = selectedDate.split("-");
var Cyear= Cdate[2];
var Cmonth= Cdate[1];
var Cday= Cdate[0];
var CYMDDate = Cyear + '-' + Cmonth + '-' + Cday;
var newdateses= new Date(CYMDDate);
var SelectedDateStrToTime=newdateses.getTime();
if((SelectedDateStrToTime>=StartDateStrToTime) && (SelectedDateStrToTime<=EndDateStrToTime))
{}
else
{
alert("Please Select date between "+StartDate+" to " +EndDates+".");
$("#selected_date").val(EndDates);
}
I have one datepicker with numberOfMonths set to 2.
Arrival Date and Departure Date are determined using this logic (within onSelect):
if ((count % 2)==0) {
depart = $("#datepicker-1").datepicker('getDate');
if (arriv > depart) { temp=arriv; arriv=depart; depart=temp; }
$("#check-in").val($.datepicker.formatDate("DD, MM d, yy",arriv));
$("#check-out").val($.datepicker.formatDate("DD, MM d, yy",depart));
} else {
arriv = $("#datepicker-1").datepicker('getDate');
depart = null;
if ((arriv > depart)&&(depart!=null)) { temp=arriv; arriv=depart; depart=temp; }
$("#day-count").val('');
$("#check-in").val($.datepicker.formatDate("DD, MM d, yy",arriv));
$("#check-out").val($.datepicker.formatDate("DD, MM d, yy",depart));
}
if(depart!=null) {
diffDays = Math.abs((arriv.getTime() - depart.getTime())/(oneDay));
if (diffDays == 0) { $("#day-count").val((diffDays+1)+' Night/s'); } else { $("#day-count").val(diffDays+' Night/s'); }
}
Getting the number of days within these 2 dates has no problem
What I want now is highlight those dates starting from the Arrival to Departure
I tried working around the onSelect but had no luck.
I am now using beforeShowDay to highlight these dates but I can't seem to figure it out
Got a sample from here
Basically, it is customized to highlight 11 or 12 days after the selected date (Here's the code from that link).
$('#datePicker').datepicker({beforeShowDay: function(date) {
if (selected != null && date.getTime() > selected.getTime() &&
(date.getTime() - selected.getTime())
Since I am new to using the UI, and the logic is not clear to me yet, I can't seem to figure this out. Any ideas on how I can make this highlight dates between the Arrival and Departure using my aforementioned logic used in determining the two?
Super old question but I came across the answer for anyone that finds this: http://jsfiddle.net/kVsbq/4/
JS
$(".datepicker").datepicker({
minDate: 0,
numberOfMonths: [12, 1],
beforeShowDay: function (date) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
},
onSelect: function (dateText, inst) {
var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input1").val());
var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#input2").val());
if (!date1 || date2) {
$("#input1").val(dateText);
$("#input2").val("");
$(this).datepicker();
} else {
$("#input2").val(dateText);
$(this).datepicker();
}
}
});
IF this helps.. :-)
$(function() {
var togo=['10/25/2013']
var datesArray=['10/27/2013','10/28/2013']
var datesArray1=['10/25/2013','10/26/2013']
var datesArray2=['10/24/2013']
$( "#datepicker" ).datepicker({
numberOfMonths: 2,
selectMultiple:true,
beforeShowDay: function (date) {
var theday = (date.getMonth()+1) +'/'+
date.getDate()+ '/' +
date.getFullYear();
return [true,$.inArray(theday, datesArray2) >=0?"specialDate":($.inArray(theday, datesArray)>=0?"specialDate2":($.inArray(theday, datesArray1)>=0?"specialDate1":''))];
},
onSelect: function(date){
console.log("clicked"+date);
return [true,$.inArray(['10/24/2013'], togo) >=0?"specialDate":($.inArray(date, datesArray1)>=0?"specialDate1":'')] ;
}
});
//$.inArray(theday, datesArray) >=0?"specialDate":'specialDate1'
});
http://jsfiddle.net/pratik24/Kyt2w/3/
Not quite an answer, but this may be useful:
http://www.eyecon.ro/datepicker/
Rather unfortunately named, but it seems like it could be what you need.