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.
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);
});
I am having fromdate and todate I want if user enters the from date and to date the gap between them should not be ore then 20 days. i.e if user enters from date='30/08/2018' to date='26/09/2018' here the gap is more then 20 days so i want to show a alert using jquery.
Below is my code
var today = new Date(new Date().getFullYear(), new Date().getMonth(),new Date().getDate());
$('#startdate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
maxDate : function() {
return $('#enddate').val();
}
});
$('#enddate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
minDate : function() {
return $('#startdate').val();
}
});
handle onchanged event in both the inputs and make a function 'checkDates()' which will compare the two dates and if the difference is more then 20 days make alert() .See the example code below
<input id="startdate" onchanged="checkDate()"/>
<input id="enddate" onchanged="checkDate()"/>
<script>
function checkDate(){
var start = $('#startdate').val();
var end = $('#enddate').val();
//convert strings to date for comparing
var startDate = new Date(start);
var endDate = new Date(end);
// Calculate the day diffrence
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((endDate.getTime() - startDate.getTime()) / (oneDay));
if(diffDays > 20){
alert("Days are more then twenty");
}
}
</script>
Please let me know if it worked.
Try this.....
<input id="startDate" onchanged="myFunction()"/>
<input id="endDate" onchanged="myFunction()"/>
<script>
function myFunction(){
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if(diffDays > 20){
alert("Days are more then twenty");
}
}
</script>
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 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.
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" />