I am calculating the age from jquery datepicker. But this works when only the date is in(mm/dd/yy) format. I need to get this working in dd/mm/yy.
//Code
$('#dob').datepicker({
onSelect: function(value, ui) {
var today = new Date(),
dob = new Date(value),
age = new Date(today - dob).getFullYear() - 1970;
$('#age').text(age);
},
maxDate: '+0d',
yearRange: '1920:2010',
changeMonth: true,
changeYear: true
});
If i try to set dateFormat: 'mm/dd/yy' in the property this wont work.
Any help?
Demo Fiddle mm/dd/yy Demo Fiddle dd/mm/yy
jQuery
onSelect: function (value, ui) {
var today = new Date();
var format = value.split("/");
var dob = new Date(format[2], format[0], format[1]);
var diff = (today - dob);
var age = Math.floor(diff / 31536000000);
$('#age').text(age);
},
Reference
Hope it helps....
Try this:
http://jsfiddle.net/lotusgodkk/GCu2D/120/
Js:
$('#dob').datepicker({
onSelect: function(value, ui) {
console.log(ui.selectedYear)
var today = new Date(),
dob = new Date(value),
age = ui.selectedYear - 1970; //This is the update
$('#age').text(age);
},
maxDate: '+0d',
yearRange: '1920:2010',
changeMonth: true,
changeYear: true,
});
If you inspect the ui object in console, you'll see that it stores year,day,month separately. You can access them like ui.selectedDay or selectedYear . Hope this helps.
this answer will work fine for the all the dates as the month starts from 0 in date function. for date format(dd-mm-yy).
var now= new Date();
var year= now.getFullYear();
$('#dob').datepicker({
onSelect: function (value, ui) {
var today = new Date();
console.log(today.getFullYear());
var format = value.split("-");
console.log(format[2]);
var dob = new Date(format[2], format[1]-1, format[0]);
console.log(dob);
var diff = (today - dob);
var age = Math.floor(diff / 31536000000);
$('#age').text(age);
},
dateFormat: 'dd-mm-yy',
maxDate: '+0d',
yearRange: '1920:'+year,
changeMonth: true,
changeYear: true
});
$("#dob").datepicker({
onSelect: function (value, ui) {
debugger
var today = new Date();
var year = today.getFullYear() - ui.selectedYear;
var month = today.getMonth() - ui.selectedMonth;
var date = today.getDate() - ui.selectedDay;
if ((year == 0 && month == 0 && date < 0) || (year == 0 && month < 0) || (year < 0)) {
$("#lbl6").show();
$("#age").val("");
} else if ((year == 0) || (year > 0 && month == 0 && date >= 0) || (year > 0 && month > 0)) {
$("#age").val(year);
} else if ((year > 0 && month == 0 && date < 0) || (year > 0 && month < 0)) {
$("#age").val(year - 1);
}
},
dateFormat: 'dd M y',
changeMonth: true,
changeYear: true,
yearRange: '1900:2020'
});
Related
I am trying to exclude Array Dates and Sundays in Dependent Datepicker.
The first datepicker works really well while the second datepicker doesn't exclude Array dates and sundays in Maxdate.
Second datepicker must selectable within 7 working days which should exclude Sunday and Array Dates.
I believe there's should be an easy way to achieve this.
Any Suggestion?
Here's the code :(
$(document).ready(function() {
var d = new Date();
var array = ["10-12-2019","05-12-2019"];
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
today = monthNames[d.getMonth()] + ' ' + d.getDate() + ' ' + d.getFullYear();
function includeDate(date) {
var dateStr = jQuery.datepicker.formatDate('dd-mm-yy', date);
// Date 0 = Sunday & 6 = Saturday
return date.getDay() !== 0 && array.indexOf(dateStr) === -1;
}
function getTomorrow(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
}
$('#datepicker2').attr('readonly', 'readonly');
$('#datepicker1').datepicker(
{
defaultDate: "+1d",
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: 1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = new Date();
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
return max + extra;
})
(3)
});
$('#datepicker1').change(function () {
var from = $('#datepicker1').datepicker('getDate');
var date_diff = Math.ceil((from.getTime() - Date.parse(today)) / 86400000);
var maxDate_d = date_diff + 7 +'d';
date_diff = date_diff + 'd';
$('#datepicker2').val('').removeAttr('readonly').removeClass('hasDatepicker').datepicker({
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: date_diff +1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = $('#datepicker1').datepicker('getDate');
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
return max + extra;
})
(7)
});
});
});
http://jsfiddle.net/nLveychs/83/
For your code, it is almost right. You just forgot one thing for the second date picker. That is, you did not add the date_diff value to the return value of the maxDate() anonymous function. I was going to pass the date_diff by adding it to the parameter. Nonetheless, I found a bug. It can't be done that way, because any previous un-selectable days, will turn into additional extra days. Thus, the only way to add date_diff is start from the day of date picker1 and add the return value of maxDate's anonymous function to date_diff.
I also took out some unnecessary codes. You can just get the date differences simply subtracting datepicker1 date to today date without needing to parse a date string. Plus, date_diff can be as was without needing a "d" to be added to it.
Also, take note that, when you calculate the different days between two dates, for your code, it work that way, because datepicker's date picked object is set to the 0 hour of the day. That code may not work for other scenario. The for sure way to get the day difference between two dates is by setting their hours, minutes, seconds, and milliseconds(if needed) to zeroes.
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
$(document).ready(function() {
var array = ["10-12-2019","05-12-2019"];
function includeDate(date) {
var dateStr = jQuery.datepicker.formatDate('dd-mm-yy', date);
// Date 0 = Sunday & 6 = Saturday
return date.getDay() !== 0 && array.indexOf(dateStr) === -1;
}
function getTomorrow(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
}
$('#datepicker2').attr('readonly', 'readonly');
$('#datepicker1').datepicker(
{
defaultDate: "+1d",
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: 1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = new Date();
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
return max + extra;
})
(3)
});
$('#datepicker1').change(function () {
var from = $('#datepicker1').datepicker('getDate');
// Date diff can be obtained like this without needing to parse a date string.
var date_diff = Math.ceil((from - new Date()) / 86400000);
$('#datepicker2').val('').removeAttr('readonly').removeClass('hasDatepicker').datepicker({
inline: true,
showOtherMonths: true,
changeMonth: true,
selectOtherMonths: true,
required: true,
showOn: "focus",
numberOfMonths: 1,
minDate: date_diff + 1,
beforeShowDay: function(date) {
return [includeDate(date)];
},
maxDate: (function(max) {
var nextAvailable = $('#datepicker1').datepicker('getDate');
var count = 0;
var extra = 0;
while(count < max) {
nextAvailable = getTomorrow(nextAvailable);
if ( !includeDate(nextAvailable) ) {
extra++;
} else {
count++;
}
}
/*
* Date diffent have to be added to return value.
*/
return max + date_diff + extra;
})
(7)
});
});
});
</script>
<p>datepicker1 <input id="datepicker1"></p>
<p>datepicker2 <input id="datepicker2"></p>
How is it possible to calculate the total days using interval intitial and final DatePicker. Sorry for my bad english
$(".datepicker").datepicker({
minDate: 0,
numberOfMonths: [3,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());
var selectedDate = $.datepicker.parseDate($.datepicker._defaults.dateFormat, dateText);
if (!date1 || date2) {
$("#input1").val(dateText);
$("#input2").val("");
$(this).datepicker();
} else if( selectedDate < date1 ) {
$("#input2").val( $("#input1").val() );
$("#input1").val( dateText );
$(this).datepicker();
} else {
$("#input2").val(dateText);
$(this).datepicker();
}
}
});
http://jsfiddle.net/sWbfk
One way to compute date difference in days is the following:
var t1 = Date.parse($("#input1").val()); // date1.getTime();
var t2 = Date.parse($("#input2").val()); // date2.getTime();
var difference = Math.abs(t2 - t1) / 86400000;
$("#diff").val(difference);
(I tested by putting the code as the last lines of onSelect: function(dateText, inst)).
86400000 is the computed for 24h x 60min x 60s x 1000ms (number of milliseconds in a day)
When you are dealing with dates you should look into moment.js.
You can try something like this:
Moment
moment($("#input1").val()).diff(moment(selectedDate), "days");
Pure JS
var d1 = new Date(date1);
var d2 = new Date(selectedDate);
var secInDays = 24 * 60 * 60 * 1000;
d1.setHours(0, 0, 0, 0);
d2.setHours(0, 0, 0, 0);
console.log((+d2 - +d1) / secInDays)
I am stuck in between with my problem of "How to calculate the days between the dates excluding the Weekends(SAT,SUN) and the National Holidays." and really struggling to calculate the weekends and nationaldays holidays both as the same time.
Any Help would be severely appreciated.
I have arrived to the conclusion in my code , that i am getting the calculated days where i am able to exclude the weekends , but not the national holidays, I have tried to built but failed. Please let me know how to calculate both the weekends and national holidays simultaneously.
This is my html code:
<label>Leave From</label>
<input name="from" id="from" type="text" class="form-control" value="" / >
</div>
<div class="form-group" id="to_date">
<label>To</label>
<input name="to" id="to" type="text" class="form-control" >
</div>
<input type="text" id="hasil" name="hasil" readonly />
This is my script:
<script>
var disabledDays = ["3-24-2015", "3-25-2015"];
function nationalDays(date) {
var m = date.getMonth(),
d = date.getDate(),
y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, disabledDays) != -1 || new Date() > date) {
return [false];
}
}
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}
$(function () {
$("#from").datepicker({
minDate:0,
changeMonth: true,
constrainInput: true,
numberOfMonths: 1,
beforeShowDay: $.datepicker.noWeekends,
onSelect: calculateDays,
onClose: function (selectedDate) {
var day = $("#from").datepicker('getDate');
$("#to").datepicker("option", "minDate", selectedDate);
},
}).on("changeDate",function(ev){
var fromdate = new Date(ev.date);
fromdate.setMonth(fromdate.getMonth()+1);
var finaldate = fromdate.getFullYear()+"-"+fromdate.getMonth()+"-"+fromdate.getDate();
console.log(finaldate);
$("#fromdate").val(finaldate);
});
});
$(function () {
$("#to").datepicker({
minDate:0,
beforeShowDay: $.datepicker.noWeekends,
changeMonth: true,
constrainInput: true,
numberOfMonths: 1,
onSelect: calculateDays,
onClose: function (selectedDate) {
$("#from").datepicker("option", "maxDate", selectedDate);
},
}).on("changeDate",function(ev){
var todate = new Date(ev.date);
todate.setMonth(todate.getMonth()+1);
var finaldate = todate.getFullYear()+"-"+todate.getMonth()+"-"+todate.getDate();
console.log(finaldate);
$("#todate").val(finaldate);
});
});
function calculateDays(startDate, endDate) {
var form = this.form
var startDate = document.getElementById("from").value;
var startDate = new Date(startDate);
var endDate = document.getElementById("to").value;
var endDate = new Date(endDate);
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var oneDay = 24 * 60 * 60 * 1000;
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / oneDay);
var weeks = Math.floor(days / 7);
var days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (endDate < startDate) {
return 0;
}
if (startDay - endDay > 1) days = days - 2;
if (days) document.getElementById("hasil").innerHTML = days;
$("#hasil").val(days);
}
</script>
Here is the link to jsfiddle: https://jsfiddle.net/8ww4noja/2/
I would like to highlight date ranges on a jQuery datepicker.
var dates = new Array();
dates[0] = [new Date(2014,2,23), new Date(2014,2,30)];
dates[1] = [new Date(2014,2,13), new Date(2014,2,20)];
$(function() {
$('#datepicker').datepicker({
numberOfMonths: 1,
minDate: '-0m',
beforeShowDay: function (date) {
for (i=0;i<dates.length;i++) {
var date1 = dates[i][0];
var date2 = dates[i][1];
return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
}
}
})
});
The above doesn't work since only one range is visible. How can I get a loop going so that it highlights more than one range? Thanks for your help!
Fiddle
The problem is that you have the return inside the loop
for that reason on the end of the first loop the function is returning true or false
You should do something like:
var dates = new Array();
dates[0] = [new Date(2014,2,23), new Date(2014,2,30)];
dates[1] = [new Date(2014,2,13), new Date(2014,2,20)];
$(function() {
$('#datepicker').datepicker({
numberOfMonths: 1,
minDate: '-0m',
beforeShowDay: function (date) {
var bool = true;
for (i=0;i<dates.length;i++) {
var date1 = dates[i][0];
var date2 = dates[i][1];
bool = bool && date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : "";
}
return bool;
}
})
});
Try
var dates = new Array();
dates[0] = [new Date(2014, 2, 23), new Date(2014, 2, 30)];
dates[1] = [new Date(2014, 2, 13), new Date(2014, 2, 20)];
$(function () {
$('#datepicker').datepicker({
numberOfMonths: 1,
minDate: '-0m',
beforeShowDay: function (date) {
var flag = false,
date1, date2, i;
for (i = 0; i < dates.length; i++) {
date1 = dates[i][0];
date2 = dates[i][1];
flag = (!date1 || date.getTime() >= date1.getTime()) && (!date2 || date.getTime() <= date2.getTime())
if (flag) {
break;
}
}
return [true, flag ? "dp-highlight" : ""];
}
})
});
Demo: Fiddle
I wonder how to set next month with showing only mondays active:
i tried to do smth like that but it wont work
function onlyMondaysNextMonth(date){
var day = date.getDay();
var mDate = date.getMonth() + 1;
return {
minDate: mDate,
}
return [(day == 1),''];
}
Thank you.
Use the following code to enable only Mondays starting from next month
var minDate = null;
var now = new Date();
if (now.getMonth() == 11) {
minDate = new Date(now.getFullYear() + 1, 0, 1);
} else {
minDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}
/* create datepicker */
jQuery(document).ready(function () {
jQuery('#datepicker').datepicker({
minDate: minDate,
constrainInput: true,
beforeShowDay: beforeShowDay
});
});
function beforeShowDay(date) {
var day = date.getDay();
if (day == 1)
return [true]
return [false];
}
The working sample is hosted in http://elangovanr.com/samples/jquery/datepickermonday.html for your reference.