jQuery UI Datepicker difference in days - javascript

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" />

Related

I would like to know how many seconds are in a certain range [duplicate]

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);

How to get the date difference between two date pickers on clicking the second date picker?

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);
});

get the date difference for different format [duplicate]

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);

How to calculate age from jquery datepicker?

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.

jquery date comparison for uk date format

Is there a relatively straightforward way to do a date comparison, using jquery, on a UK formatted date? I'm trying to check if the number of days selected via a date input field is greater than or equal to a set number. Unfortunately I can't change the date format and need to work with dd/mm/yy.
UPDATE: the date I am working with is already in UK format dd/mm/yy - I am trying to convert this into a format which can be compared with the current date, to find number of days elapsed.
Working solution:
function checkDaysElapsed (input) {
var datePart = input.split("/");
year = datePart[2]; // get only two digits
month = datePart[1];
day = datePart[0];
var date1 = new Date(year,month-1,day);
var currentTime = new Date();
var month2 = currentTime.getMonth();
var day2 = currentTime.getDate();
var year2 = currentTime.getFullYear();
var date2 = new Date(year2,month2,day2);
console.log(year + '/' + month + '/' + day);
console.log(year2 + '/' + month2 + '/' + day2);
delta = date2 - date1;
// delta is the difference in milliseconds
delta_in_days = Math.round(delta / 1000 / 60 / 60/ 24);
return delta_in_days;
}
After you have the date in the correct format, you will also need to compare it to the other date. To do this, you might want to cast the date string to a Date() object.
Also note, that as soon as you have created a Date object, the actual format is no longer relevant.
First you need to split the date into its components, using string.split('/')
var date1 = new Date(year,month-1,day),
var date2 = new Date(year2,month2-1,day2);
delta = date2 - date1;
// delta is the difference in milliseconds
delta_in_days = Math.round(delta / 1000 / 60 / 60/ 24);
use this plugin to format the dates to pass to the server via ajax for accurate date comparission formatDate
and call like this
var start = $.format.date($('#startDate').val(), "dd/MM/yyyy");
var finish= $.format.date($('#finish').val(), "dd/MM/yyyy");
$.ajax({
cache: true,
type: 'post',
async: false,
data: { start: start, finish: finish },
url: '/controller/CheckDates',
success: function (msg) {
//msg will be the days
}
});
I've done it this way due to inaccuracies from experience, there may be a more efficient way
this is how you set the date format to dd/mm/yy:
$(function () {
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
});

Categories

Resources