Reputation: 106
I have a scenario that the page displays user's age (30) at particular date (example, 09/10/2015). Now on selection of new date, I have to pre-populate new age field with the business logic of when the new date is greater than 6 months/ 182 days (example 03/11/2016) from the given date, then age should be +1 (example age would be 31).
I know we can achieve this by following code. But I am looking for an optimal way of getting new age on selection of new date.
var newDate = $("#NewDate").val();
if (newDate != null && newDate != '') {
var currDCD = new Date($("#CurrentDate").val());
var newDCD = new Date(newDate);
var yearsDiff = newDCD.getFullYear() - currDCD.getFullYear();
var day = 1000 * 60 * 60 * 24;
//Get last years days difference
var daysDiff = Math.floor((newDCD.setFullYear(currDCD.getFullYear() + (yearsDiff - 1)) - currDCD) / day);
var currAge = parseInt($("#CurrentAge").val());
//Set new owner age
$("#NewAge").val(currAge + (daysDiff > 182 ? yearsDiff : yearsDiff-1));
}
Upvotes: 1
Views: 134
Reputation: 106
Updated and working code. Thanks Danilo.
var newDate = $("#NewDate").val();
if (newDate != null && newDate != '') {
var currDCD = new Date($("#CurrentDate").val());
var newDCD = new Date(newDate);
var diff = new Date(newDCD - currDCD);
var ageDiff = diff.getFullYear() - 1970 + (diff.getMonth() >= 6 ? 1 : 0);
var currAge = parseInt($("#CurrentOwnerAge").val());
$("#NewAge").val(currAge + ageDiff);
Upvotes: 0
Reputation: 2686
Something like this should give you the age rounded down or up depending on the month:
function getAge(birthday) {
var diff = new Date(new Date() - new Date(birthday))
return diff.getFullYear() - 1970 + (diff.getMonth()>=6?1:0)
}
where birthday is anything that can be used in the constructors of Date
Upvotes: 1