I want to calculate age when date is selected by using jquery date picker. I added code below but it showing minus value if i select date like '19/03/2015','15/01/2015' or '19/03/2014' ,'31/12/2014'
$(document).ready(function ()
{
console.log($(document).width());
$('#patientDob').datepicker
({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
yearRange: '1900:2150',
maxDate: new Date(),
inline: true,
onSelect: function() {
var birthDay = document.getElementById("patientDob").value;
var DOB = new Date(birthDay);
var today = new Date();
var age = today.getTime() - DOB.getTime();
age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));
document.getElementById('patientAge').value = age;
}
});
});
I have created this age calculator for my project
using jQuery UI. and JavaScript function. you will get the exact result.
It it will calculate age and display as human readable.
create a date field with ID 'datepicker'and import jquery and jquery ui . After that
Then just copy and paste the code to get the exact result.
output // 28 years 7 months 7 days
$(function () {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
showAnim: 'slideDown',
dateFormat: 'yy-mm-dd'
}).on('change', function () {
var age = getAge(this);
/* $('#age').val(age);*/
console.log(age);
alert(age);
});
function getAge(dateVal) {
var
birthday = new Date(dateVal.value),
today = new Date(),
ageInMilliseconds = new Date(today - birthday),
years = ageInMilliseconds / (24 * 60 * 60 * 1000 * 365.25 ),
months = 12 * (years % 1),
days = Math.floor(30 * (months % 1));
return Math.floor(years) + ' years ' + Math.floor(months) + ' months ' + days + ' days';
}
});
AFAIK The javascript Date requires yyyy/mm/dd, and you are sending:
var DOB = new Date(birthDay); // dateFormat: 'dd/mm/yy'
Change format to "yyyy/mm/dd" and will work ok.
Related
I just want to show the date difference between two jquery date pickers. The differnce should be shown on clicking the second date picker. Following is my code.
<input type ="text" id="Date">
<input type ="text" id="Date2">
$(function () {
var select=function(dateStr) {
var d1 = $('#Date').datepicker('getDate');
var d2 = $('Date2').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
alert(diff);
}
$("#Date").datepicker({
autoclose: true,
todayHighlight: true,
onSelect: select
}).datepicker('update', new Date());
$("#Date2").datepicker({
autoclose: true,
todayHighlight: true,
onSelect: select
}).datepicker('update', new Date());
});
Can anyone help me out?
You can use datepicker's onSelect event , which triggers when a date is being changed on a datapicker.
I also see that you have a typo, , replace var d2 = $('Date2').datepicker('getDate');
with var d2 = $('#Date2').datepicker('getDate');
Something like this:
$("#Date2").datepicker({
onSelect: function(value, date) {
var d1 = $('#Date').datepicker('getDate');
var d2 = $('#Date2').datepicker('getDate');
var diff = 0;
if (d1 && d2) {
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
alert(diff);
}
});
I think the following code will work
$("#Date2").bind('change keyup', function() {
var date1 = $('#Date').datepicker('getDate');
var date2 = $(this).datepicker('getDate');
var dayDiff = Math.ceil((date2 - date1) / (1000 * 60 * 60 * 24));
alert(dayDiff);
});
Please check this JSFIDDLE and help me to solve below issue. I am really stuck on this.
If I select first calendar value is 19(tuesday). I need result like 20,21,22,23 with back shade(light color).
In below code If nights = 4 and arrival = 2 the result showing in calendar is correct. But, If nights = 4 and arrival = 6 the result showing in calendar is wrong. please check attached images.
// hotel nights.. available is 2, 3, 4, 5, 6, 7, 8, 9 nights.
var nights = 4;
// arrival weekday in hotel: monday = 1, tuesday = 2, wednesday = 3, thursday = 4, friday = 5, saturday =6, sunday = 7
var arrival = 2;
nights = 4 and arrival = 2
nights = 4 and arrival = 6
Finally issue solved. Click Here
Updated script
function initializeBooking() {
$('#form_booking').ajaxSubmit({
target: '#result',
success: function () {
$('#result').fadeIn('slow');
}
});
return false;
}
// hotel nights.. available is 2, 3, 4, 5, 6, 7, 8, 9 nights.
var nights = 2;
// arrival weekday in hotel: monday = 1 ..... sunday = 7
var arrival = 7;
// flexbooking = no .. otherwise you can arrive when you want.
var flex_booking = 'no';
var couter = arrival + nights;
var diff = 0;
if(couter>7)
diff = couter-7;
$(function () {
cal_start = new Date();
cal_start.setTime(cal_start.getTime() + (24 * 60 * 60 * 1000 * 1));
$("#datepicker_begin").datepicker({
showWeek: true,
beforeShowDay: function (date) {
weekday = date.getDay();
if (weekday == 0)
weekday = 7;
if (flex_booking == 'no') {
if (weekday == arrival) {
result = [true, "relevant"]; // clickable for the arrival day
} else if (weekday > arrival && weekday <= (arrival + nights)) {
result = [false, "relevant"]; // red but no clickable for the days you are staying in the hotel
} else {
result = [false, ""]; // normal days outside the booking range. could be possible nights > 6 that this is not set and everything is red
}
if(diff>0 && weekday<=diff)
{
result = [false, "relevant"];
}
} else {
result = [true, "relevant"];
}
return result;
},
altField: "#date_begin",
altFormat: "#",
showOtherMonths: false,
selectOtherMonths: false,
numberOfMonths: 3,
dateFormat: "dd.mm.yy",
firstDay: 1,
minDate: cal_start,
maxDate: "+12m",
onSelect: function () {
begin = eval($("#date_begin").val());
start = new Date();
start.setTime(begin);
days = nights;
end = new Date();
end.setTime(begin + (24 * 60 * 60 * 1000 * days));
$("#date_end").val(begin + (24 * 60 * 60 * 1000 * days));
after = new Date();
after.setTime(begin + (24 * 60 * 60 * 1000 * days) + (24 * 60 * 60 * 1000));
$("#datepicker_end").val(('0' + end.getDate()).slice(-2) + '.' + ('0' + (end.getMonth() + 1)).slice(-2) + '.' + end.getFullYear());
$("#nights_span").html(new Date(end - begin) / 1000 / 60 / 60 / 24);
$("#datepicker_end").datepicker("destroy");
$("#datepicker_end").datepicker({
beforeShowDay: function (date) {
return [false, ""];
},
altField: "#date_end",
altFormat: "#",
minDate: new Date(end),
maxDate: new Date(after),
showOtherMonths: false,
selectOtherMonths: false,
numberOfMonths: 1,
dateFormat: "dd.mm.yy",
firstDay: 1,
onSelect: function (dateText) {
initializeBooking();
}
});
initializeBooking();
}
});
});
This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 7 years ago.
How do I get the difference between 2 dates in full days (I don't want any fractions of a day)
var date1 = new Date('7/11/2010');
var date2 = new Date('12/12/2010');
var diffDays = date2.getDate() - date1.getDate();
alert(diffDays)
I tried the above but this did not work.
Here is one way:
const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");
Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.
A more correct solution
... since dates naturally have time-zone information, which can span regions with different day light savings adjustments
Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.
You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.
Now, the solution can be written as,
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
// test it
const a = new Date("2017-01-01"),
b = new Date("2017-07-25"),
difference = dateDiffInDays(a, b);
console.log(difference + ' days')
This works because UTC time never observes DST. See Does UTC observe daylight saving time?
p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.
var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10);
alert(diffDays )
I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....
So here's my answer and can be run out of the box.
<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {
$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})
$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end = $('#enddate').datepicker('getDate');
if (start<end) {
var days = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>
a Fiddle can be seen here DEMO
This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.
var dat1 = document.getElementById('inputDate').value;
var date1 = new Date(dat1)//converts string to date object
alert(date1);
var dat2 = document.getElementById('inputFinishDate').value;
var date2 = new Date(dat2)
alert(date2);
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
alert(diffDays);
this javascript calculate worng number of the days
i select two dates
1st date 2013-01-01
2nd date 2013-12-31
and it is showing worng answer 365 days
i was calculte manual it is worng correct answer is 364 days
how can i fix this issue please help me
thanks
live demo
form
<input class='fromdate' />
<input class='todate' />
<input class='calculated' />
<input class='minim' /><br/><p><font size="3"><b>For more FAQs Visit<a target="_blank"href="http://jqfaq.com/"</a> JQFaq.com</b></font></p>
<iframe id="iframe1" src="http://jqfaq.com/AdPage.html" style="width:100%; height:115px; border:none;"
/>
javascript
$('.fromdate').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
$('.todate').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
$('.fromdate').datepicker().bind("change", function () {
var minValue = $(this).val();
minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
$('.todate').datepicker("option", "minDate", minValue);
calculate();
});
$('.todate').datepicker().bind("change", function () {
var maxValue = $(this).val();
maxValue = $.datepicker.parseDate("yy-mm-dd", maxValue);
$('.fromdate').datepicker("option", "maxDate", maxValue);
calculate();
});
function calculate() {
var d1 = $('.fromdate').datepicker('getDate');
var d2 = $('.todate').datepicker('getDate');
var diff = 1;
if (d1 && d2) {
diff = diff + Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
}
$('.calculated').val(diff);
$('.minim').val(d1)
}
Like this way you can do it -
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
Refer this
Try this to calculate the "diff" in function calculate():
if (d1 && d2) {
var timeDiff = Math.abs(d2.getTime() - d1.getTime());
diff = Math.ceil(timeDiff / (1000 * 3600 * 24));
}
In your code the var diff=1 is causing problem.
change it to var diff=1 then see you will get 364 days.
I need to calculate the number of weeks difference between the chosen date and the current date. I've tried to calculate with weekNumberPicked - weekNumberCurrent, but if the two dates are in different years, the result is incorrect, so I probably need to get it like daysDifference / 7. How should I implement this with the onSelect action?
You can use the Datepicker's function getDate to get a Date object.
Then just subtract one date from the other (might want to get the absolute value as well) to get the milliseconds in difference, and calculate the difference in days, or weeks.
$('#test').datepicker({
onSelect: function() {
var date = $(this).datepicker('getDate');
var today = new Date();
var dayDiff = Math.ceil((today - date) / (1000 * 60 * 60 * 24));
}
});
Since DatePicker getDate() methode returns a javascript Date object, you can do something like :
var myDate = $('.datepicker').datepicker('getDate');
var current = new Date();
var difference = myDate - current;
difference now contains the number of milliseconds between your two dates
, you can easily compute the number of weeks :
var weeks = difference / 1000 / 60 / 60 / 24 / 7;
try this code and applied it to your work :D
$("#date_born").datepicker({
onSelect: function () {
var start = $('#date_born').datepicker('getDate');
var end = new Date();
var age_year = Math.floor((end - start)/31536000000);
var age_month = Math.floor(((end - start)% 31536000000)/2628000000);
var age_day = Math.floor((((end - start)% 31536000000) % 2628000000)/86400000);
$('#age').val(age_year +' year ' + age_month + ' month ' + age_day + ' day');
},
dateFormat: 'dd/mm/yy',
maxDate: '+0d',
yearRange: '1914:2014',
buttonImageOnly: false,
changeMonth: true,
changeYear: true
});
Html Code:
Date <input type="text" name="date_born" id="date_born"/>
Age <input type="text" name="age" id="age" />