Reputation: 727
I want do show from user date birthday that a few days and months and years last.
Here is my code, as taken from here: Calculate age in JavaScript
How can it continue with the month and day, as:
user birthday is : 2010/04/29
The result should be like this: 2 years, 4 months, 5 days old.
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
alert(getAge('2010/04/29'));
DEMO: http://jsfiddle.net/jFxb5/
Upvotes: 12
Views: 61786
Reputation: 59
// Make a button that display the current date and time in local format on the page.
function mydateis(){
const d = new Date();
let text = d.toLocaleString();
document.getElementById("date").innerHTML = text;
var year_born = prompt("Please enter your date of birth:", 1998);
var month_born = prompt("Please enter your month:", 1);
var month_day = prompt("Please enter your day:", 1);
function getAge(birthYear,month_born,month_day){
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentmonth = currentDate.getMonth();
var currentday = currentDate.getDate();
console.log(currentDate);
console.log(currentDate.getDate());
age = currentYear - birthYear;
month = currentmonth - month_born;
day = currentday - month_day;
return age,month,day;
}
calculatedAge = getAge(year_born,month_born,month_day);
document.getElementById("yearsold").innerHTML ="you have yeyre is" + age+ " and "+month+" month and days is "+day ;
}
Upvotes: 0
Reputation: 46
this code return array [minutes_ago,hours_ago,days_ago,month_ago,years_ago]
function get_minutes_ago(time_minutes){
if (time_minutes < 60)
{
return [time_minutes,0];
}else{
return [0,0];
}
}
function get_hours_ago(time_minutes){
if (time_minutes < (24 * 60) )
{
return [time_minutes / (60), (time_minutes % 60)];
}else{
return [0,0];
}
}
function get_days_ago(time_minutes){
if (time_minutes < (30 * 24 * 60) )
{
return [time_minutes / (24*60),(time_minutes % (24*60))];
}else{
return [0,0];
}
}
function get_month_ago(time_minutes){
if ( time_minutes < (12 * 30 * 24 * 60) )
{
return [time_minutes / (30*24*60),time_minutes % (30*24*60)];
}else{
return [0,0];
}
}
function get_years_ago(time_minutes){
if (time_minutes >= (12 * 30 * 24 * 60) )
{
return [time_minutes / (12*30*24*60),time_minutes % (12*30*24*60)];
}else{
return [0,0];
}
}
function getAge(dateString) {
tmp = new Date(dateString);
now = new Date();
var diff = now.getTime() - tmp.getTime();
var total_minutes = Math.floor(diff/60/1000)
var minutes_ago = 0;
var hours_ago = 0;
var days_ago = 0;
var month_ago = 0;
var years_ago = 0;
if ( total_minutes >= (12*30*24*60) ){
years_ago = get_years_ago(total_minutes)[0];
month_ago = get_month_ago(get_years_ago(total_minutes)[1])[0];
days_ago = get_days_ago(get_month_ago(get_years_ago(total_minutes)[1])[1])[0];
hours_ago = get_hours_ago(get_days_ago(get_month_ago(get_years_ago(total_minutes)[1])[1])[1])[0];
minutes_ago = get_minutes_ago(get_hours_ago(get_days_ago(get_month_ago(get_years_ago(total_minutes)[1])[1])[1])[1])[0];
}
if( total_minutes < (12*30*24*60) && total_minutes >= (30*24*60))
{
month_ago = get_month_ago(total_minutes)[0];
days_ago = get_days_ago(get_month_ago(total_minutes)[1])[0];
hours_ago = get_hours_ago(get_days_ago(get_month_ago(total_minutes)[1])[1])[0];
minutes_ago = get_minutes_ago(get_hours_ago(get_days_ago(get_month_ago(total_minutes)[1])[1])[1])[0];
}
if (total_minutes < (30*24*60) && total_minutes >= (24*60)){
days_ago = get_days_ago(total_minutes)[0];
hours_ago = get_hours_ago(get_days_ago(total_minutes)[1])[0];
minutes_ago = get_minutes_ago(get_hours_ago(get_days_ago(total_minutes)[1])[1])[0];
}
if( total_minutes < (24*60) && total_minutes >= 60){
hours_ago = get_hours_ago(total_minutes)[0];
minutes_ago = get_minutes_ago(get_hours_ago(total_minutes)[1])[0];
}
if(total_minutes < 60){
minutes_ago = get_minutes_ago(total_minutes)[0];
}
return [Math.floor(minutes_ago),Math.floor(hours_ago),Math.floor(days_ago),Math.floor(month_ago),Math.floor(years_ago)];
}
usage
getAge( Date.now() - ( 24 * 60 * 60 * 1000 ) ); // for return [0, 0, 1, 0, 0]
getAge(Date.now() - ( 30 * 24 * 60 * 60 * 1000 )) // for return [0, 0, 0, 1, 0]
or
var ss = new Date("2010/2/2");
getAge(ss.getTime()) // return [30, 9, 14, 6, 12]
Upvotes: 0
Reputation: 557
let dt = dob;
let age = '';
let bY = Number(moment(dt).format('YYYY'));
let bM = Number(moment(dt).format('MM'));
let bD = Number(moment(dt).format('DD'));
let tY = Number(moment().format('YYYY'));
let tM = Number(moment().format('MM'));
let tD = Number(moment().format('DD'));
age += (tY - bY) + ' Y ';
if (tM < bM) {
age += (tM - bM + 12) + ' M ';
tY = tY - 1;
} else {
age += (tM - bM) + ' M '
}
if (tD < bD) {
age += (tD - bD + 30) + ' D ';
tM = tM - 1;
} else {
age += (tD - bD) + ' D '
}
//AGE MONTH DAYS
console.log(age);
Upvotes: 0
Reputation: 73
Answered by @ygssoni is partially correct. Rest you can do:
Instead of using 31 while calculating days:
if (dateNow >= dateDob)
var dateAge = dateNow - dateDob;
else {
monthAge--;
var dateAge = 31 + dateNow - dateDob;
if (monthAge < 0) {
monthAge = 11;
yearAge--;
}
}
I have corrected this: Write this function and use it inside getAge() function.
function daysInMonth (month, year) {
return new Date(year, month, 0).getDate();
}
if (dateNow >= dateDob)
var dateAge = dateNow - dateDob;
else {
monthAge--;
noOfDaysInDOB = daysInMonth(monthDob,yearDob);
var dateAge = noOfDaysInDOB + dateNow - dateDob;
if (monthAge < 0) {
monthAge = 11;
yearAge--;
}
}
Created video tutorial in Hindi for the same: https://youtu.be/TnOwcvppV6U
Upvotes: 0
Reputation: 11
This function will give the age in years, months and days. It works by calculating the difference in months first, then adding that number to the date of birth, and then calculating the difference in days. The beauty of this is that it is left to the Date object to worry about leap years and difference in days in each month.
var nowDate = new Date(new Date().setHours(0, 0, 0, 0));
// Example date of birth.
var dobDate = new Date["03/31/2001"];
var years = nowDate.getFullYear() - dobDate.getFullYear();
var months = nowDate.getMonth() - dobDate.getMonth();
var days = nowDate.getDate() - dobDate.getDate();
// Work out the difference in months.
months += years * 12;
if (days < 0) {
months -= 1;
}
// Now add those months to the date of birth.
dobDate.setMonth(dobDate.getMonth() + months);
// Calculate the difference in milliseconds.
var diff = nowDate - dobDate;
// Divide that by 86400 to get the number of days.
var days = Math.round(diff / 86400 / 1000);
// Now convert months back to years and months.
years = parseInt(months / 12);
months -= (years * 12);
// Format age as "xx years, yy months, zz days"
var text = "";
if (years) {
text = years + (years > 1 ? " years" : " year");
}
if (months) {
if (text.length) {
text = text + ", ";
}
text = text + months + (months > 1 ? " months" : " month")
}
if (days) {
if (text.length) {
text = text + ", ";
}
text = text + days + (days > 1 ? " days" : " day")
}
if (nowDate == dobDate) {
text = "Newborn"
}
return text;
Upvotes: 1
Reputation:
For those who don't want to be restricted by format mm/dd/yyyy
, you can replace:
var dob = new Date(dateString.substring(6,10),
dateString.substring(0,2)-1,
dateString.substring(3,5)
);
with:
var dob = new Date(dateString);
This allows me to use use 2012/09/30 and still get the right answer.
Upvotes: 1
Reputation: 351308
As I saw an issue with the accepted solution (see my comment there), I present here my own version, which guarantees there will be no "jumps" in the number of days when increasing the date of birth by only 1.
This code defines a more generic DateInterval
class for representing the difference between two dates. The function getAge
then becomes a thin implementation based on that class.
class DateInterval {
constructor(start, end) { // two Date instances
if (start > end) [start, end] = [end, start]; // swap
this.days = end.getDate() - start.getDate();
this.months = end.getMonth() - start.getMonth();
this.years = end.getFullYear() - start.getFullYear();
if (this.days < 0) {
// Add the number of days that are left in the month of the start date
this.days += (new Date(start.getFullYear(), start.getMonth() + 1, 0)).getDate();
this.months--;
}
if (this.months < 0) {
this.months += 12;
this.years--;
}
}
toString() {
const arr = ["years", "months", "days"].map(p =>
this[p] && (this[p] + " " + p.slice(0, this[p] > 1 ? undefined : -1))
).filter(Boolean);
if (!arr.length) return "0 days";
const last = arr.pop();
return arr.length ? [arr.join(", "), last].join(" and ") : last;
}
}
function getAge(dateString) {
let today = new Date();
today.setHours(0,0,0,0);
let dob = new Date(dateString);
dob.setHours(0,0,0,0);
return new DateInterval(dob, today) + " old.";
}
// Demo: increment the date of birth by 1 at each test:
let d = new Date(2000, 1, 1);
setInterval(() => {
const s = d.toJSON().slice(0,10);
console.log("Someone born on " + s + " is now " + getAge(s));
d = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1);
}, 300);
Upvotes: 2
Reputation: 347
Try this:
function getAge(dateString) {
var today = new Date();
var DOB = new Date(dateString);
var totalMonths = (today.getFullYear() - DOB.getFullYear()) * 12 + today.getMonth() - DOB.getMonth();
totalMonths += today.getDay() < DOB.getDay() ? -1 : 0;
var years = today.getFullYear() - DOB.getFullYear();
if (DOB.getMonth() > today.getMonth())
years = years - 1;
else if (DOB.getMonth() === today.getMonth())
if (DOB.getDate() > today.getDate())
years = years - 1;
var days;
var months;
if (DOB.getDate() > today.getDate()) {
months = (totalMonths % 12);
if (months == 0)
months = 11;
var x = today.getMonth();
switch (x) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: {
var a = DOB.getDate() - today.getDate();
days = 31 - a;
break;
}
default: {
var a = DOB.getDate() - today.getDate();
days = 30 - a;
break;
}
}
}
else {
days = today.getDate() - DOB.getDate();
if (DOB.getMonth() === today.getMonth())
months = (totalMonths % 12);
else
months = (totalMonths % 12) + 1;
}
var age = years + ' years ' + months + ' months ' + days + ' days';
return age;
}
console.log(getAge("2010/02/28"));
console.log(getAge("2010/03/01"));
Upvotes: 3
Reputation: 1
function CalculateAge(DobString) {
$("#age").val(getAge(DobString));
}
function getAge(dateString) {
var now = new Date('2019/01/20');
var today = new Date(now.getYear(), now.getMonth(), now.getDate());
var yearNow = now.getYear();
var monthNow = now.getMonth();
var dateNow = now.getDate();
var dob = new Date(dateString.substring(6, 10),
dateString.substring(3, 5) - 1,
dateString.substring(0, 2)
);
var yearDob = dob.getYear();
var monthDob = dob.getMonth();
var dateDob = dob.getDate();
var age = {};
var ageString = "";
var yearString = "";
var monthString = "";
var dayString = "";
yearAge = yearNow - yearDob;
if (monthNow >= monthDob)
var monthAge = monthNow - monthDob;
else {
yearAge--;
var monthAge = 12 + monthNow - monthDob;
}
if (dateNow >= dateDob)
var dateAge = dateNow - dateDob;
else {
monthAge--;
var dateAge = 31 + dateNow - dateDob;
if (monthAge < 0) {
monthAge = 11;
yearAge--;
}
}
age = {
years: yearAge,
months: monthAge,
days: dateAge
};
if (age.years > 1) yearString = " years";
else yearString = " year";
if (age.months > 1) monthString = " months";
else monthString = " month";
if (age.days > 1) dayString = " days";
else dayString = " day";
if ((age.years > 0) && (age.months > 0) && (age.days > 0))
ageString = age.years + yearString + ", " + age.months + monthString + " " + age.days + dayString + " ";
else if ((age.years == 0) && (age.months == 0) && (age.days > 0))
ageString = " " + age.days + dayString + " ";
else if ((age.years > 0) && (age.months == 0) && (age.days == 0))
ageString = age.years + yearString + " ";
else if ((age.years > 0) && (age.months > 0) && (age.days == 0))
ageString = age.years + yearString + " " + age.months + monthString + " ";
else if ((age.years == 0) && (age.months > 0) && (age.days > 0))
ageString = age.months + monthString + " " + age.days + dayString + " ";
else if ((age.years > 0) && (age.months == 0) && (age.days > 0))
ageString = age.years + yearString + " " + age.days + dayString + " ";
else if ((age.years == 0) && (age.months > 0) && (age.days == 0))
ageString = age.months + monthString + " ";
else ageString = "Oops! Could not calculate age!";
return ageString;
}
Upvotes: 0
Reputation: 21
Calculates age in terms of years, months and days. Enter the dates in any valid date string format such as '1952/09/28', 'Sep 29, 1952', '09/28/1952' etc.
Takes 2 arguments - date of birth and the date on which to calculate age. You can leave the second argument out for today's date. Returns an object with years, months and days properties of age.
Uses the solar year value of 365.2425 days in a year.
@param birthDate Date of birth. @param ageAtDate The date on which to calculate the age. None for today's date. @returns {{years: number, months: number, days: number}}
function getAge(birthDate, ageAtDate) {
var daysInMonth = 30.436875; // Days in a month on average.
var dob = new Date(birthDate);
var aad;
if (!ageAtDate) aad = new Date();
else aad = new Date(ageAtDate);
var yearAad = aad.getFullYear();
var yearDob = dob.getFullYear();
var years = yearAad - yearDob; // Get age in years.
dob.setFullYear(yearAad); // Set birthday for this year.
var aadMillis = aad.getTime();
var dobMillis = dob.getTime();
if (aadMillis < dobMillis) {
--years;
dob.setFullYear(yearAad - 1); // Set to previous year's birthday
dobMillis = dob.getTime();
}
var days = (aadMillis - dobMillis) / 86400000;
var monthsDec = days / daysInMonth; // Months with remainder.
var months = Math.floor(monthsDec); // Remove fraction from month.
days = Math.floor(daysInMonth * (monthsDec - months));
return {years: years, months: months, days: days};
}
Upvotes: 1
Reputation: 7359
function getAge(dateString) {
var now = new Date();
var today = new Date(now.getYear(),now.getMonth(),now.getDate());
var yearNow = now.getYear();
var monthNow = now.getMonth();
var dateNow = now.getDate();
var dob = new Date(dateString.substring(6,10),
dateString.substring(0,2)-1,
dateString.substring(3,5)
);
var yearDob = dob.getYear();
var monthDob = dob.getMonth();
var dateDob = dob.getDate();
var age = {};
var ageString = "";
var yearString = "";
var monthString = "";
var dayString = "";
yearAge = yearNow - yearDob;
if (monthNow >= monthDob)
var monthAge = monthNow - monthDob;
else {
yearAge--;
var monthAge = 12 + monthNow -monthDob;
}
if (dateNow >= dateDob)
var dateAge = dateNow - dateDob;
else {
monthAge--;
var dateAge = 31 + dateNow - dateDob;
if (monthAge < 0) {
monthAge = 11;
yearAge--;
}
}
age = {
years: yearAge,
months: monthAge,
days: dateAge
};
if ( age.years > 1 ) yearString = " years";
else yearString = " year";
if ( age.months> 1 ) monthString = " months";
else monthString = " month";
if ( age.days > 1 ) dayString = " days";
else dayString = " day";
if ( (age.years > 0) && (age.months > 0) && (age.days > 0) )
ageString = age.years + yearString + ", " + age.months + monthString + ", and " + age.days + dayString + " old.";
else if ( (age.years == 0) && (age.months == 0) && (age.days > 0) )
ageString = "Only " + age.days + dayString + " old!";
else if ( (age.years > 0) && (age.months == 0) && (age.days == 0) )
ageString = age.years + yearString + " old. Happy Birthday!!";
else if ( (age.years > 0) && (age.months > 0) && (age.days == 0) )
ageString = age.years + yearString + " and " + age.months + monthString + " old.";
else if ( (age.years == 0) && (age.months > 0) && (age.days > 0) )
ageString = age.months + monthString + " and " + age.days + dayString + " old.";
else if ( (age.years > 0) && (age.months == 0) && (age.days > 0) )
ageString = age.years + yearString + " and " + age.days + dayString + " old.";
else if ( (age.years == 0) && (age.months > 0) && (age.days == 0) )
ageString = age.months + monthString + " old.";
else ageString = "Oops! Could not calculate age!";
return ageString;
}
alert(getAge('09/09/1989'));
Upvotes: 35