days left until user's bday - javascript

I've created a pirate speak program.
It asks the user for their name and date of birth and calculates the years from the input and added 100 years for fun. I also need to calculate the number of days left until their birthday using user input but I don't know what to do. I've tried some methods and stuff but its not working. any tips or mistakes I need to fix?
var name = prompt('What\'s yer name?');
var date = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
let years = date;
let num = years.substring(6, 10);
var myInput = parseInt(num);
var x = myInput;
var y = 100;
var result = x + y;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
var myInput = parseInt(date);
var bday = myInput;
function daysUntilNext(month, day){
var tday= new Date(), y= tday.getFullYear(), next= new Date(y, month-1, day);
tday.setHours(0, 0, 0, 0);
if(tday>next) next.setFullYear(y+1);
return Math.round((next-tday)/8.64e7);
}
var d= daysUntilNext(date);
console.log(d+' day'+(d>1? 's': '')+' until yer birthday');

Ok, I have cleaned up your JavaScript a little. Best practice was to get the date from the string and parse each part then just create a Date object from there. What's easier in the future is to use a datepicker HTML component rather than a string, but I understand that wasn't your goal for this.
Next, do the plus 100 calculation and display that result.
Lastly, take the Date object we made and take the information that we need from it. FWIW getDay() returns the day of the week, you want getDate() which return the day of the month. Then calculate how many days away from those in the next year. Display that result in the console.
I think you were getting that NAN because you were doing calculations on strings not numbers or it was because there weren't enough parameters in daysUntilNext(), so you were operating on null or undefined somewhere
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var daySubstring = birthDateString.substring(3, 5);
var monthSubstring = birthDateString.substring(0, 2);
var yearSubstring = birthDateString.substring(6, 10);
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');

The other answerer's code is correct, but not clear. Here's the same, only more user-friendly.
The difference is that single-digit months or days won't bother you.
I hope I could help.
var name = prompt('What\'s yer name?');
var birthDateString = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
var inputdate = birthDateString.split("/");
var daySubstring = inputdate[1];
var monthSubstring = inputdate[0];
var yearSubstring = inputdate[2];
var birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));
var ONE_HUNDRED = 100;
var result = parseInt(yearSubstring) + ONE_HUNDRED;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
function daysUntilNext(month, day) {
var today = new Date();
var year = today.getFullYear();
var next = new Date(year, month, day);
today.setHours(0, 0, 0, 0);
if (today > next) next.setFullYear(year + 1);
return Math.round((next - today) / 8.64e7);
}
var d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());
console.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');

Related

How to check if the date having more than one year from current year

I am trying to check if the date i.e. (07/02/2018 ) is more than year from current date and if the date i.e. (07/02/2018 ) is less than year from current date using JavaScript tried with following code
var x = new Date('JUN-2016');
var y = new Date('MAY-2016');
console.log(+x < +y);
Your question is not very clear to me but this may help you:
var now = new Date();
var then = new Date('07/02/2018');
var diffInDays = Math.round((then-now) / (1000*60*60*24));
console.log('then is', diffInDays, 'days more than now.');
Note: If diffInDays is a positive number then the then is more than now, otherwise it's less.
You can simply add 1000*60*60*24*365 milliseconds to your first date and compare it to your second date :
var x = new Date('APR-2015');
var y = new Date('MAY-2016');
console.log(+x + 1000*60*60*24*365 < +y);
var x2 = new Date('SEP-2015');
console.log(+x2 + 1000*60*60*24*365 < +y);
You can get the year with the getFullYear()method (Date doc).
let x = new Date();
let y = new Date();
x_year = x.getFullYear();
y_year = y.getFullYear();
// The you just have to compare the year
One way to do it, although I'd be surprised if there wasn't a better way:
var x = new Date();
x = x.setFullYear(x.getFullYear() + 1);
x = new Date(x);
var y = (new Date('2018-04-08'));
var z = (new Date('2019-04-08'));
if (y < x) {
console.log('Y is less than a year from now');
} else {
console.log('Y is more or exactly a year from now');
}
if (z < x) {
console.log('Z is less than a year from now');
} else {
console.log('Z is more or exactly a year from now');
}
Your question is not clear this is based on my assumption.
I am assuming that you need to check if the given date is one year ahead of the current date.
var x = new Date('1, 1, 2018');
var today = new Date();
var time = Math.abs(today.getTime() - x.getTime());
var days = Math.ceil(time / (1000 * 3600 * 24));
alert("There is a difference of " + days + " days between today and the given date");
I am assuming that you want to know if some arbitrary date is less or more than a year from current date.
We can get a the value for a year this way:
var a_year = Math.abs(new Date('01-01-2018'.replace(/-/g,'/')) - new Date('01-01-2017'.replace(/-/g,'/')));
Then we set two date tests:
var test1 = '01-01-2018';
var test2 = '01-01-2015';
Calculate the diffs:
var diff1 = Math.abs(new Date() - new Date(test1.replace(/-/g,'/')));
var diff2 = Math.abs(new Date() - new Date(test2.replace(/-/g,'/')));
Then you can log the results for testing:
console.log(diff1 > a_year)
console.log(diff1 < a_year)
console.log(diff2 > a_year)
console.log(diff2 < a_year)
Credits to David Hedlund's answer on How to subtract date/time in javascript?

how to compare a user entered date to the current date and change a fields background color?

I am new to javascript and am working on a fallible PDF form and trying to set it to do multiple things. The first is I need to compare a user entered date to the current date to see if it is withing 5 years to the day. The second thing I need it to do is to change a fields background color if that date is at the 5 year time or outside of that range. This is the code I have been trying but it hasn't worked so far. There are 37 fields that need to be checked by this.
for(i=1;i<38;i++){
var Y = d.getFullYear();
var d = new Date();
var M = d.getMonth();
var d = new Date();
var D = d.getDay(); //n =2
var strDate = this.getField("Text"+[i]).value;
var arrDate = strDate.split('/');
var month = arrDate[0];
var day = arrDate[1];
var year = arrDate[2];
if(year+5>=Y){
if(M<=month){
if(D<=day){
this.getField("Text[i]").fillColor=color.red;
}}}}
I have updated this, it working now, can you try this now ?
for(i=1;i<38;i++)
{
var todayDate = new Date();
var strDate = "12/25/2009";
var arrDate = strDate.split('/');
var month = arrDate[0];
var day = arrDate[1];
var year = parseInt(arrDate[2]) + 5;
var userEnteredDate = new Date(year, month, day);
if(userEnteredDate <= todayDate)
{
//Color change code here...
}
}
The simplest approach so far as I know, is to instantiate a Date that is five years ago based on current time:
var t = new Date()
t.setFullYear(t.getFullYear() - 5) // t is five years ago
Then you just need to substract the user input date with this one, and see if the result is positive or negative:
var ut = new Date("......") // the Date instance from user input
if(ut - t >= 0) {
// within 5 years
} else {
// more than 5 years ago
}
The reason you can do so, is because when you substract two Date instances one another, they will be internally converted to timestamps. The less a timestamp is, the earlier the time is. So the result of substraction (a number) represents the time in between, in milliseconds.
If you don't care how long in between, you could just compare them:
var ut = new Date("......") // the Date instance from user input
if(ut >= t) {
// within 5 years
} else {
// more than 5 years ago
}
Try this
var d = new Date(),
Y = d.getFullYear(),
M = d.getMonth() + 1, // since this returns 0 - 11
D = d.getDay() + 1, // since this returns 0 - 30
strDate,
arrDate,
month,
day,
year;
for(var i = 1; i < 38; i++) {
strDate = this.getField("Text" + i).value;
arrDate = strDate.split('/');
month = parseInt(arrDate[0], 10);
day = parseInt(arrDate[1], 10);
year = parseInt(arrDate[2], 10);
if (((Y + 5) * 12 + M < year * 12 + month) || ((Y + 5) * 12 + M === year * 12 + month && D < day)) {
this.getField("Text" + i).fillColor = color.red;
}
}

javascript age calculator keep giving wrong numbers,

i am trying to do a javascript program and calculate the age for the use, i have done the code below,
function submitForm() {
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var days = d.getDay();
var minutes = d.getMinutes();
var hours = d.getHours();
var byear = document.dataform.year.selectedIndex;
var bmonth = document.dataform.month.selectedIndex;
var bday = document.dataform.day.selectedIndex;
var bhours = bday * 24;
var bmin = 60 * b hours;
var dyears = year - byear;
var dmonth = month - bmonth;
var ddays = (days - bday);
var dhours = hours - bhours;
var dminutes = minutes - bmin;
var daysTillBDay = 365 - bday;
if (isLeapYear() == true) {
dyears = year - byear;
dmonth = month - bmonth;
ddays = (days - bday) + 1;
dhours = hours - bhours;
dminutes = minutes - bmin;
daysTillBDay = 365 - bday;
}
var el = document.getElementsByName('uyears');
el[0].value = dyears + " years old.";
el = document.getElementsByName('umonths');
el[0].value = dmonth + " months old.";
document.getElementsByName('udays')[0].value = ddays;
document.getElementsByName('lmonths')[0].value = dmonth;
document.getElementsByName('ldays')[0].value = ddays;
document.getElementsByName('lhrs')[0].value = dhours;
document.getElementsByName('lmin')[0].value = dminutes;
document.getElementsByName('bdays')[0].value = daysTillBDay + " days left till your birthday.";
}
I think i will be work before i try to run the program, after i run the program, i found that the program give me almost everthing wrong, i have the year like 2013(newest yrs.), and the month i will equal the negativetive number such as -1 if i enter 11. I just try to find users age, which i believe is the date of today(today's gate)-(the birthday date), but is not workng now, anyobne know what>?
The problem is very simple (and one mistake that I've made myself) - new Date().getDay() returns the day in the week (0 for Monday, through to 6 for Sunday), not the day in the month.
The function that you're looking for is new Date().getDate(), which returns 1 for January the 1st, 25 on Christmas Day, and so on.

Javascript: wrong date calculation

So I just have posted a question about this code (which was answered):
$(document).ready(Main);
function Main() {
ConfigDate();
}
function ConfigDate() {
var currentTime = new Date();
var dayofWeek = currentTime.getDay();
var daysSinceThursday = (dayofWeek + 3) % 7
var lastThursday = new Date(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
$("#last_thursday").text(yyyy + " / " + mm + " / " + dd);
}
The problem now is that the date that appears in my cell is 1969 / 12 / 31 (which isn't even a thursday).
Did I do something wrong while calculating last thursday date?
This is because .getDate() returns the day of the month. So you are building your date based on a serial number of something less than 30, which won't even set your seconds above 1.
Use .setDate() instead of building a new date:
date.setDate(date.getDate() - daysSinceThursday);
.setDate() will modify your existing date object, it doesn't return a new date.
You're trying to set a Date based only on the day of the month of the last Thursday. Try something like this:
var daysSinceThursday = (dayofWeek + 3) % 7;
var lastThursday = new Date(currentTime.getTime());
lastThursday.setDate(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
http://jsfiddle.net/rAuRF/3/

How can I calculate the number of years between two dates?

I want to get the number of years between two dates. I can get the number of days between these two days, but if I divide it by 365 the result is incorrect because some years have 366 days.
This is my code to get date difference:
var birthday = value;//format 01/02/1900
var dateParts = birthday.split("/");
var checkindate = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);
var thisyear = new Date().getFullYear();
var birthyear = dateParts[2];
var number_of_long_years = 0;
for(var y=birthyear; y <= thisyear; y++){
if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {
number_of_long_years++;
}
}
The day count works perfectly. I am trying to do add the additional days when it is a 366-day year, and I'm doing something like this:
var years = ((days)*(thisyear-birthyear))
/((number_of_long_years*366) + ((thisyear-birthyear-number_of_long_years)*365) );
I'm getting the year count. Is this correct, or is there a better way to do this?
Sleek foundation javascript function.
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday;
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Probably not the answer you're looking for, but at 2.6kb, I would not try to reinvent the wheel and I'd use something like moment.js. Does not have any dependencies.
The diff method is probably what you want: http://momentjs.com/docs/#/displaying/difference/
Using pure javascript Date(), we can calculate the numbers of years like below
document.getElementById('getYearsBtn').addEventListener('click', function () {
var enteredDate = document.getElementById('sampleDate').value;
// Below one is the single line logic to calculate the no. of years...
var years = new Date(new Date() - new Date(enteredDate)).getFullYear() - 1970;
console.log(years);
});
<input type="text" id="sampleDate" value="1980/01/01">
<div>Format: yyyy-mm-dd or yyyy/mm/dd</div><br>
<button id="getYearsBtn">Calculate Years</button>
No for-each loop, no extra jQuery plugin needed... Just call the below function.. Got from Difference between two dates in years
function dateDiffInYears(dateold, datenew) {
var ynew = datenew.getFullYear();
var mnew = datenew.getMonth();
var dnew = datenew.getDate();
var yold = dateold.getFullYear();
var mold = dateold.getMonth();
var dold = dateold.getDate();
var diff = ynew - yold;
if (mold > mnew) diff--;
else {
if (mold == mnew) {
if (dold > dnew) diff--;
}
}
return diff;
}
I use the following for age calculation.
I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.
/**
* Calculates human age in years given a birth day. Optionally ageAtDate
* can be provided to calculate age at a specific date
*
* #param string|Date Object birthDate
* #param string|Date Object ageAtDate optional
* #returns integer Age between birthday and a given date or today
*/
gregorianAge = function(birthDate, ageAtDate) {
// convert birthDate to date object if already not
if (Object.prototype.toString.call(birthDate) !== '[object Date]')
birthDate = new Date(birthDate);
// use today's date if ageAtDate is not provided
if (typeof ageAtDate == "undefined")
ageAtDate = new Date();
// convert ageAtDate to date object if already not
else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
ageAtDate = new Date(ageAtDate);
// if conversion to date object fails return null
if (ageAtDate == null || birthDate == null)
return null;
var _m = ageAtDate.getMonth() - birthDate.getMonth();
// answer: ageAt year minus birth year less one (1) if month and day of
// ageAt year is before month and day of birth year
return (ageAtDate.getFullYear()) - birthDate.getFullYear()
- ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate()))?1:0)
}
<input type="text" id="birthDate" value="12 February 1982">
<div style="font-size: small; color: grey">Enter a date in an acceptable format e.g. 10 Dec 2001</div><br>
<button onClick='js:alert(gregorianAge(document.getElementById("birthDate").value))'>What's my age?</button>
Little out of date but here is a function you can use!
function calculateAge(birthMonth, birthDay, birthYear) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth();
var currentDay = currentDate.getDate();
var calculatedAge = currentYear - birthYear;
if (currentMonth < birthMonth - 1) {
calculatedAge--;
}
if (birthMonth - 1 == currentMonth && currentDay < birthDay) {
calculatedAge--;
}
return calculatedAge;
}
var age = calculateAge(12, 8, 1993);
alert(age);
You can get the exact age using timesstamp:
const getAge = (dateOfBirth, dateToCalculate = new Date()) => {
const dob = new Date(dateOfBirth).getTime();
const dateToCompare = new Date(dateToCalculate).getTime();
const age = (dateToCompare - dob) / (365 * 24 * 60 * 60 * 1000);
return Math.floor(age);
};
let currentTime = new Date().getTime();
let birthDateTime= new Date(birthDate).getTime();
let difference = (currentTime - birthDateTime)
var ageInYears=difference/(1000*60*60*24*365)
Yep, moment.js is pretty good for this:
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
getYears(date1, date2) {
let years = new Date(date1).getFullYear() - new Date(date2).getFullYear();
let month = new Date(date1).getMonth() - new Date(date2).getMonth();
let dateDiff = new Date(date1).getDay() - new Date(date2).getDay();
if (dateDiff < 0) {
month -= 1;
}
if (month < 0) {
years -= 1;
}
return years;
}
for(var y=birthyear; y <= thisyear; y++){
if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {
days = days-366;
number_of_long_years++;
} else {
days=days-365;
}
year++;
}
can you try this way??
function getYearDiff(startDate, endDate) {
let yearDiff = endDate.getFullYear() - startDate.getFullYear();
if (startDate.getMonth() > endDate.getMonth()) {
yearDiff--;
} else if (startDate.getMonth() === endDate.getMonth()) {
if (startDate.getDate() > endDate.getDate()) {
yearDiff--;
} else if (startDate.getDate() === endDate.getDate()) {
if (startDate.getHours() > endDate.getHours()) {
yearDiff--;
} else if (startDate.getHours() === endDate.getHours()) {
if (startDate.getMinutes() > endDate.getMinutes()) {
yearDiff--;
}
}
}
}
return yearDiff;
}
alert(getYearDiff(firstDate, secondDate));
getAge(month, day, year) {
let yearNow = new Date().getFullYear();
let monthNow = new Date().getMonth() + 1;
let dayNow = new Date().getDate();
if (monthNow === month && dayNow < day || monthNow < month) {
return yearNow - year - 1;
} else {
return yearNow - year;
}
}
If you are using moment
/**
* Convert date of birth into age
* param {string} dateOfBirth - date of birth
* param {string} dateToCalculate - date to compare
* returns {number} - age
*/
function getAge(dateOfBirth, dateToCalculate) {
const dob = moment(dateOfBirth);
return moment(dateToCalculate).diff(dob, 'years');
};
If you want to calculate the years and keep the remainder of the time left for further calculations you can use this function most of the other answers discard the remaining time.
It returns the years and the remainder in milliseconds. This is useful if you want to calculate the time (days or minutes) left after you calculate the years.
The function works by first calculating the difference in years directly using *date.getFullYear()*.
Then it checks if the last year between the two dates is up to a full year by setting the two dates to the same year.
Eg:
oldDate= 1 July 2020,
newDate= 1 June 2022,
years =2020 -2022 =2
Now set old date to new date's year 2022
oldDate = 1 July, 2022
If the last year is not up to a full year then the year is subtracted by 1, the old date is set to the previous year and the interval from the previous year to the current date is calculated to give the remainder in milliseconds.
In the example since old date July 2022 is greater than June 2022 then it means a full year has not yet elapsed (from July 2021 to June 2022) therefore the year count is greater by 1. So years should be decreased by 1. And the actual year count from July 2020 to June 2022 is 1 year ,... months.
If the last year is a full year then the year count by *date.getFullYear()* is correct and the time that has elapsed from the current old date to new date is calculated as the remainder.
If old date= 1 April, 2020, new date = 1 June, 2022 and old date is set to April 2022 after calculating the year =2.
Eg: from April 2020 to June 2022 a duration of 2 years has passed with the remainder being the time from April 2022 to June 2022.
There are also checks for cases where the two dates are in the same year and if the user enters the dates in the wrong order the new Date is less recent than the old Date.
let getYearsAndRemainder = (newDate, oldDate) => {
let remainder = 0;
// get initial years between dates
let years = newDate.getFullYear() - oldDate.getFullYear();
if (years < 0) {// check to make sure the oldDate is the older of the two dates
console.warn('new date is lesser than old date in year difference')
years = 0;
} else {
// set the old date to the same year as new date
oldDate.setFullYear(newDate.getFullYear());
// check if the old date is less than new date in the same year
if (oldDate - newDate > 0) {
//if true, the old date is greater than the new date
// the last but one year between the two dates is not up to a year
if (years != 0) {// dates given in inputs are in the same year, no need to calculate years if the number of years is 0
console.log('Subtracting year');
//set the old year to the previous year
years--;
oldDate.setFullYear(oldDate.getFullYear() - 1);
}
}
}
//calculate the time difference between the old year and newDate.
remainder = newDate - oldDate;
if (remainder < 0) { //check for negative dates due to wrong inputs
console.warn('old date is greater than new Date');
console.log('new date', newDate, 'old date', oldDate);
}
return { years, remainder };
}
let old = new Date('2020-07-01');
console.log( getYearsAndRemainder(new Date(), old));
Date calculation work via the Julian day number. You have to take the first of January of the two years. Then you convert the Gregorian dates into Julian day numbers and after that you take just the difference.
Maybe my function can explain better how to do this in a simple way without loop, calculations and/or libs
function checkYearsDifference(birthDayDate){
var todayDate = new Date();
var thisMonth = todayDate.getMonth();
var thisYear = todayDate.getFullYear();
var thisDay = todayDate.getDate();
var monthBirthday = birthDayDate.getMonth();
var yearBirthday = birthDayDate.getFullYear();
var dayBirthday = birthDayDate.getDate();
//first just make the difference between years
var yearDifference = thisYear - yearBirthday;
//then check months
if (thisMonth == monthBirthday){
//if months are the same then check days
if (thisDay<dayBirthday){
//if today day is before birthday day
//then I have to remove 1 year
//(no birthday yet)
yearDifference = yearDifference -1;
}
//if not no action because year difference is ok
}
else {
if (thisMonth < monthBirthday) {
//if actual month is before birthday one
//then I have to remove 1 year
yearDifference = yearDifference -1;
}
//if not no action because year difference is ok
}
return yearDifference;
}
Bro, moment.js is awesome for this:
The diff method is what you want: http://momentjs.com/docs/#/displaying/difference/
The below function return array of years from the year to the current year.
const getYears = (from = 2017) => {
const diff = moment(new Date()).diff(new Date(`01/01/${from}`), 'years') ;
return [...Array(diff >= 0 ? diff + 1 : 0).keys()].map((num) => {
return from + num;
});
}
console.log(getYears(2016));
<script src="https://momentjs.com/downloads/moment.js"></script>
function dateDiffYearsOnly( dateNew,dateOld) {
function date2ymd(d){ w=new Date(d);return [w.getFullYear(),w.getMonth(),w.getDate()]}
function ymd2N(y){return (((y[0]<<4)+y[1])<<5)+y[2]} // or 60 and 60 // or 13 and 32 // or 25 and 40 //// with ...
function date2N(d){ return ymd2N(date2ymd(d))}
return (date2N(dateNew)-date2N(dateOld))>>9
}
test:
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*366*24*3600*1000));
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*365*24*3600*1000))
I went for the following very simple solution. It does not assume you were born in 1970 and it also takes into account the hour of the given birthday date.
function age(birthday) {
let now = new Date();
let year = now.getFullYear();
let years = year - birthday.getFullYear();
birthday = new Date(birthday.getTime()); // clone
birthday.setFullYear(year);
return now >= birthday ? years : years - 1;
}
This one Help you...
$("[id$=btnSubmit]").click(function () {
debugger
var SDate = $("[id$=txtStartDate]").val().split('-');
var Smonth = SDate[0];
var Sday = SDate[1];
var Syear = SDate[2];
// alert(Syear); alert(Sday); alert(Smonth);
var EDate = $("[id$=txtEndDate]").val().split('-');
var Emonth = EDate[0];
var Eday = EDate[1];
var Eyear = EDate[2];
var y = parseInt(Eyear) - parseInt(Syear);
var m, d;
if ((parseInt(Emonth) - parseInt(Smonth)) > 0) {
m = parseInt(Emonth) - parseInt(Smonth);
}
else {
m = parseInt(Emonth) + 12 - parseInt(Smonth);
y = y - 1;
}
if ((parseInt(Eday) - parseInt(Sday)) > 0) {
d = parseInt(Eday) - parseInt(Sday);
}
else {
d = parseInt(Eday) + 30 - parseInt(Sday);
m = m - 1;
}
// alert(y + " " + m + " " + d);
$("[id$=lblAge]").text("your age is " + y + "years " + m + "month " + d + "days");
return false;
});
if someone needs for interest calculation year in float format
function floatYearDiff(olddate, newdate) {
var new_y = newdate.getFullYear();
var old_y = olddate.getFullYear();
var diff_y = new_y - old_y;
var start_year = new Date(olddate);
var end_year = new Date(olddate);
start_year.setFullYear(new_y);
end_year.setFullYear(new_y+1);
if (start_year > newdate) {
start_year.setFullYear(new_y-1);
end_year.setFullYear(new_y);
diff_y--;
}
var diff = diff_y + (newdate - start_year)/(end_year - start_year);
return diff;
}

Categories

Resources