I have two JQuery datepicker on my page, I want to put all the days between the two dates to an array.
How Can I work it out?
Here is my snippet:
function mennyi() {
var dtFrom = document.getElementById('arrival').value;
var dtTo = document.getElementById('departure').value;
var dt1 = new Date(dtFrom);
var dt2 = new Date(dtTo);
var diff = dt2.getDate() - dt1.getDate();
var days = diff;
alert(dtTo);
document.getElementById("nights").innerHTML = days + " nights"; {
$('#arrival').datepicker({ dateFormat: 'dd-mm-yy' }).val();
$('#departure').datepicker({ dateFormat: 'dd-mm-yy' }).val();
var start = new Date(document.getElementById('arrival').value),
end = new Date(document.getElementById('departure').value),
currentDate = new Date(start),
between = []
;
while (end > currentDate) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
$('#lista').html(between.join('<br> '));};
return false;
}
function isNumeric(val) {
var ret = parseInt(val);
};
Now it works, but the thing is how can I change the date format, before I put the string into the array?
Related
I am using JQuery to block some dates but next month are available.
A user can click on today day + 5 and all the other should be disabled.
What I am doing wrong?
<div id='datepicker' onchange="test(this)">
</div>
$('#datepicker').datepicker(
{
numberOfMonths: 2,
beforeShowDay: function (date) {
var hilight = [true, 'isActive'];
var today = new Date();
var blockdays = new Date();
// var startdayofmonth = new Date(today.getFullYear(), today.getMonth(), 1);
today.setDate(today.getDate() + 5);
blockdays.setDate(blockdays.getDate() + 12);
blockdays = moment(blockdays.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
var blockendofmonth = new Date(today.getFullYear(), today.getMonth() + 1, 1);;
blockendofmonth = moment(blockendofmonth.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
today = moment(today.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
date = moment(date.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
if (date < today) {
hilight = [false, ''];
}
else if (date >= blockdays) {
hilight = [false, ''];
}
return hilight;
}
}
);
Comparing dates string in YYYY-DD-MM format gives incorrect results. '2021-10-04' < '2021-20-03' this evaluated to true' which is actually not correct. When comparing date strings, it is better to follow YYYY-MM-DD:HH:MM:SS format for better result. Checkout below snippet.
$(document).ready(function () {
var allowDays = getAllowDays();
$('#datepicker').datepicker({
numberOfMonths: 2,
beforeShowDay: function (date) {
var hilight = [true, 'isActive'];
var start = allowDays[0];
var end = allowDays[1];
var currentDate = +moment(date).format('YYYYMMDD');
if (currentDate < start) {
hilight = [false, ''];
} else if (currentDate >= end) {
hilight = [false, ''];
}
return hilight;
}
});
});
function getAllowDays() {
var today = new Date();
var blockdays = new Date();
today.setDate(today.getDate() + 5);
blockdays.setDate(blockdays.getDate() + 12);
return [+moment(today).format('YYYYMMDD'), +moment(blockdays).format('YYYYMMDD')];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery.ui.datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css"/>
<div id='datepicker'></div>
I have this variable {{ $daterange }} with json like this
{
"starts_at": "2020-05-20",
"ends_at": "2020-05-23"
},
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
What I want to do is to expand something like this,
2020-05-20
2020-05-21
2020-05-22
2020-05-23
2020-05-24
2020-05-25
2020-05-26
2020-05-27
2020-05-28
2020-05-29
I'm planning to assign these dates inside of expandedDate variable
var expandedDate = [ ....dates ];
This should be done using jquery/js
UPDATE*
Recently this code works and can get all dates between 2 dates. It will list down all dates between 2 date range written in the code.
// 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(2013,10,22), new Date(2013,11,25));
dates.forEach(function(date) {
console.log(date);
});
How can I populate {{ $daterange }} contains multiple date range.
Think I missed your update with existing code. The following code seems to get the desired output using javascript. Just added comments to each step as an explanation. Hope it is helpful.
//sample input data
var daterange = [{
"starts_at": "2020-05-27",
"ends_at": "2020-06-23"
},
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
];
// function to get dates between two dates
var getDaysAsArray = function(start_date, end_date) {
for (var arr = [], d = new Date(start_date); d <= end_date; d.setDate(d.getDate() + 1)) {
arr.push(new Date(d));
}
return arr;
};
// function to convert date into the format yyyy-mm-dd
var getFormattedDay = function(date) {
day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
month = date.getMonth()+1 < 10 ? "0" + (date.getMonth()+1) : date.getMonth()+1;
year = date.getFullYear();
return year + "-" + month + "-" + day;
}
//main logic
var expandedDate = [];
//Iterate through the list of arrays in the date range
for (var key in daterange) {
//get first pair of from and to date
var from_string = daterange[key].starts_at;
var to_string = daterange[key].ends_at;
// convert the string date to date format for from and to.
var from_date = new Date(from_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
var to_date = new Date(to_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
// call getDaysAsArray to convert dates into strings and into an array.
var daylist = getDaysAsArray(from_date, to_date);
// iterate through the daylist and push it into the final array you want to use
for (var day in daylist) {
expandedDate.push(getFormattedDay(daylist[day]));
}
}
// final result required
console.log(expandedDate);
Here's the complete code on how to solve this question
Based on #thommu
var daterange = [
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
];
// function to get dates between two dates
var getDaysAsArray = function(start_date, end_date) {
for (var arr = [], d = new Date(start_date); d <= end_date; d.setDate(d.getDate() + 1)) {
arr.push(new Date(d));
}
return arr;
};
// function to convert date into the format yyyy-mm-dd
var getFormattedDay = function(date) {
day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
month = date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth();
year = date.getFullYear();
return year + "-" + month + "-" + day;
}
//main logic
var expandedDate = [];
//Iterate through the list of arrays in the date range
for (var key in daterange) {
//get first pair of from and to date
var from_string = daterange[key].starts_at;
var to_string = daterange[key].ends_at;
// convert the string date to date format for from and to.
var xfrom_date = new Date(from_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
var xto_date = new Date(to_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
//Add +1 month to correct the data
var from_date = new Date(xfrom_date.setMonth(xfrom_date.getMonth()+1));
var to_date = new Date(xto_date.setMonth(xto_date.getMonth()+1));
// call getDaysAsArray to convert dates into strings and into an array.
var daylist = getDaysAsArray(from_date, to_date);
// iterate through the daylist and push it into the final array you want to use
for (var day in daylist) {
expandedDate.push(getFormattedDay(daylist[day]));
}
}
//Filter Duplicated Dates
var dateDuplicate = expandedDate;
var uniqueDate = [];
$.each(dateDuplicate, function(i, el){
if($.inArray(el, uniqueDate) === -1) uniqueDate.push(el);
});
// final result required
console.log(uniqueDate);
I have a datepicker in JS where I disabled passed dates AND only allow saturdays like this:
$(document).ready(function(){
$("#aankomstdatum").datepicker({
dateFormat: "dd-mm-yy",
numberOfMonths:2,
minDate: 0,
beforeShowDay: function(date){
var day = date.getDay();
return [day == 6];
}});
});
I also have a code that lets me disable specific dates like this:
/** Days to be disabled as an array */
var disableddates = ["26-05-2018"];
function DisableSpecificDates(date) {
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
// First convert the date in to the mm-dd-yyyy format
// Take note that we will increment the month count by 1
var currentdate = (m + 1) + '-' + d + '-' + y ;
// We will now check if the date belongs to disableddates array
for (var i = 0; i < disableddates.length; i++) {
// Now check if the current date is in disabled dates array.
if ($.inArray(currentdate, disableddates) != -1 ) {
return [false];
}
}
}
With adding this, it works:
beforeShowDay: DisableSpecificDates
The issue I have is that i can't make both work. I'm not sure How can disable the past dates and all days except saturdays AND also disable specific given dates in the array, while seperatly they do work. I always get syntax errors when trying for example:
beforeShowDay: DisableSpecificDates, function(date){
var day = date.getDay();
return [day == 6];
}});
Is this possible to do?
Yes, it's possible to achieve this. You want to create one function and return [false] from it if:
date is a Saturday or
date is contained within disableddates array
Here's the example:
var disableddates = ["26-04-2018"];
function DisableDates(date) {
var selectable = !isSaturday(date) && !isDateDisabled(date);
return [selectable];
}
function isSaturday(date) {
var day = date.getDay();
return day === 6;
}
function isDateDisabled(date) {
var m = date.getMonth() + 1;
var d = date.getDate();
var y = date.getFullYear();
// First convert the date in to the dd-mm-yyyy format
if(d < 10) d = '0' + d;
if(m < 10) m = '0' + m;
var currentdate = d + '-' + m + '-' + y;
// Check if disableddates array contains the currentdate
return disableddates.indexOf(currentdate) >= 0;
}
And then just pass DisableDates function as the value of your beforeShowDay option:
$("#aankomstdatum").datepicker({
dateFormat: "dd-mm-yy",
numberOfMonths:2,
minDate: 0,
beforeShowDay: DisableDates
});
This is my code
const date = new Date();
const startDate = new Date(date.getFullYear(), date.getMonth(), 1);
const endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
const getDateArray = function(start, end) {
const arr = [];
const dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
const dateArr = getDateArray(startDate, endDate);
in this above code I got the current month date list dateArr, Now I need to group the days by a week, from the week list I need to filter only week start date and weekend date that must be in list formate I tried with the above code but I cant proceed to next.
This works.
var date = new Date();
console.log("All Weeks : ", getWeeksInaMonth())
console.log("Current Week : ", getCurrentWeek())
console.log("Current and previous weeks : ",getCurrAndPrevWeeks())
function getFormattedDate(dateobj)
{
var date = dateobj.getDate(), month = dateobj.getMonth()+1, year = dateobj.getFullYear();
var formattddate = (date<10?"0":"")+date+"/"+(month<10?"0":"")+month+"/"+year;
return formattddate;
}
function getWeeksInaMonth()
{
var startdate = new Date(date.getFullYear(), date.getMonth(), 1);
var enddate = new Date(date.getFullYear(), date.getMonth()+1, 0);
var weeks = [];
for(var i=1,n=enddate.getDate();i<n;)
{
startdate.setDate(i);
var arr = [getFormattedDate(startdate)];
i =i+ 6-startdate.getDay();
if(i>n) i=i-(i-n);
startdate.setDate(i);
arr.push(getFormattedDate(startdate));
i++;
weeks.push(arr);
}
return weeks
}
function getCurrentWeek()
{
var today = new Date(), day = today.getDay();
return [getFormattedDate(new Date(today.getFullYear(),today.getMonth(),today.getDate()-day)),
getFormattedDate(new Date(today.getFullYear(),today.getMonth(),today.getDate()+6-day))];
}
function getCurrAndPrevWeeks()
{
var startdate = new Date(date.getFullYear(), date.getMonth(), 1);
var enddate = new Date(date.getFullYear(), date.getMonth()+1, 0);
var today = new Date().getDate();
var weeks = [];
for(var i=1,n=enddate.getDate();i<n;)
{
startdate.setDate(i);
var arr = [getFormattedDate(startdate)];
i =i+ 6-startdate.getDay();
if(i>n) i=i-(i-n);
startdate.setDate(i);
arr.push(getFormattedDate(startdate));
weeks.push(arr);
if(today>=i-6 && today<=i) break;
i++;
}
return weeks;
}
Good day,
I'm having a little trouble with calculating number of days from now to a selected date after selecting a date from jQuery datepicker.
I think that the datepicker is changing the date formatting of the date on selection and causing the calculation to go wrong but I can't quite figure out how to counter this. I am sure it is me but I can't see the forest for the trees so any suggestions would be really helpful.
Here is the code:
<input type="text" class="datepicker-calc" />
<input type="text" id="tbAddDays" />
$(document).ready(function () {
$(".datepicker-calc").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
onSelect: function (date, e) {
var expDate = new Date(date);
var date = e.selectedDay;
if (date < 10) {
date = ("0" + e.selectedDay)
}
var month = e.selectedMonth;
if (month < 10) {
month = ("0" + e.selectedMonth)
}
var year = e.selectedYear;
var endDate = month + "/" + date + "/" + year;
updateDays(endDate, e);
$(".datepicker-calc").datepicker("hide");
}
});
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function updateDays(expDate, e) {
var now = new Date();
var startDate = now.toDateString('dd/MM/yyyy');
var exp = new Date(expDate);
var endDate = exp.toDateString('dd/MM/yyyy');
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var totalDays = (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
$('#tbAddDays').val(totalDays);
}
});
The onSelect event will receive a string in the specified format, which is dd/mm/yy. JavaScript Date.parse method will parse such dates incorrectly, or not parse them at all. The solution is to use parseDate() function built into jQuery ui:
onSelect: function (dateText, inst) {
var expDate = $.datepicker.parseDate(inst.settings.dateFormat, dateText, inst.settings);
var diff = expDate - new Date();
var days = diff / 1000 / 60 / 60 / 24;
alert( /* ceil, floor, round */ days);
}
Realised that I need the display to be in jQuery dd/mm/yy (dd/mm/yyyy) format so kept that and did some manipulation to the expDate being passed to the updateDays() method to ensure that the date to be calculated would be handled correctly by JS.
Working script:
$(".datepicker-calc").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
onSelect: function (selectdate, e) {
var newDate = selectdate.slice(0,2);
var newMonth = selectdate.slice(4,6);
if (newMonth < "10") { newMonth = ("0" + newMonth.slice(0,1));};
var newYear = selectdate.slice(6,11);
var expDate = newMonth + "/" + newDate + "/" + newYear;
updateDays(expDate, e);
$(".datepicker-calc").datepicker("hide");
}
});
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function updateDays(expDate, e) {
var now = new Date();
var startDate = now.toDateString('dd/MM/yyyy');
var expire = new Date(expDate);
var endDate = expire.toDateString('dd/MM/yyyy');
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var totalDays = (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
$('#tbAddDays').val(totalDays);
}