Home > Enterprise >  Create a function that tells us how many days, weeks and months we have left if we live until 90 yea
Create a function that tells us how many days, weeks and months we have left if we live until 90 yea

Time:10-16

// What We have to do is to Calculate Age left in weeks days months //

var yourAge=prompt("Your Age?");
var ageInDays= (yourAge-90)*365;
var ageInWeeks= (yourAge-90)*52;
var ageInMonths=(yourAge-90)*12;
function ageCalculation(yourAge){
alert("You have "   ageInDays   "Days"   ageInWeeks   "Weeks"   ageInMonths   "Months" );
}

CodePudding user response:

Calculate the difference between now and a date [age] years ago, then convert to days, hours etc.

(See also)

const age = 10;
const now = new Date();
const then = new Date(new Date(now).setFullYear(now.getFullYear() - age));
const diffFromNow = difference2Parts(now, then);

// 10 years until now
console.log(`${age} years ago until now lasted ${
  diffFromNow.months} months and ${diffFromNow.daysLeft} days`);

// for a given birthday date calculate current age
// in days, hours ... etc.
const givenDate = new Date(`2015/04/01 13:23:00`);
const difference = difference2Parts(now, givenDate);
console.log( `You where born on ${
  givenDate.toLocaleString()},\nso your live lasted ${
    difference.months} month(s), ${
      difference.daysLeft} day(s), ${difference.hoursLeft} hour(s) and ${
        difference.minutesLeft} minute(s)` );

function difference2Parts(d1, d2) {
  const milliseconds = Math.abs(d1 - d2);
  const secs = Math.floor(milliseconds / 1000);
  const mins = Math.floor(secs / 60);
  const hours = Math.floor(mins / 60);
  const days = Math.floor(hours / 24);
  const millisecs = Math.floor(Math.abs(milliseconds)) % 1000;
  const multiple = (term, n) => n !== 1 ? `${n} ${term}s` : `1 ${term}`;
  
  return {
    months: Math.abs(d1.getMonth() - d2.getMonth()   
            12 * (d2.getFullYear() - d1.getFullYear())),
    daysTotal: days,
    hoursLeft: hours % 24,
    hoursTotal: hours,
    minutesTotal: mins,
    secondsTotal: secs,
    minutesLeft: mins % 60,
    secondsLeft: secs % 60,
    milliSeconds: milliseconds,
    daysLeft: Math.abs(d1.getDate() - d2.getDate()),
    get diffStr() {
      return `${multiple(`month`, this.months)}, ${
        multiple(`day`, this.daysLeft)}, ${
        multiple(`hour`, this.hoursLeft)}, ${
        multiple(`minute`, this.minutesLeft)} and ${
        multiple(`second`, this.secondsLeft)}`;
    },
    get diffStrMs() {
      return `${this.diffStr.replace(` and`, `, `)} and ${
        multiple(`millisecond`, this.milliSeconds % 1000)}`;
    },
  };
}

CodePudding user response:

hey its not the best approach but here you go for refer. you can improve it by yourself.

var currentAge =  25//prompt('Current age : ')

function howManyWeeksLeft(){
    let lastYear = 90;
    let ageWeekCalculated = (90 - currentAge) * 52
    
    console.log( ageWeekCalculated)
    
}


howManyWeeksLeft()
  • Related