Can I find the current date using JS?

Question

Can I find the current date using JS?

Answer

We can! There are a few methods, and quirks, to know about when trying to find the current date using JavaScript.

A great method to know about is new Date() (based on the UNIX epoch, which is the number of milliseconds passed since 1 January 1970 00:00:00 UTC):

  • new Date() will return a JavaScript Date object with the following format - YYYY-MM-DDThh:mm:SS.sssZ - where the T separates the date from the time and the Z means “zero hour offset” (which is UTC)
  • JS has built in methods to format the date including:
    • .getDate(), returns the day of the month
    • .getFullYear(), returns the year
    • .getMonth(), returns the month, 0-11 (starting with 0 index)
    • …among others! Search MDN for more info about getting dates with JS and the methods used to format dates

Example usage:

const currentDate = new Date();
const currentMonth = currentDate.getMonth() + 1;
const currentDay = currentDate.getDate();
const currentYear = currentDate.getFullYear();

console.log(`Today's date (m/dd/yyyy): ${currentMonth}/${currentDay}/${currentYear}`);
3 Likes

When we reason it out, there is really no need to declare any of these variables as constants since that makes them not re-usable. With var we at least have the ability to redefine them.

4 Likes

Why will you need to redefine current variables? Otherwise it will neither be the current year, nor current month, nor current day.

The moment they were defined they were frozen in time. Date.now() changes every millionth of a second. The above is confined to a single instant in time and never changes its timeframe. Alright, one supposes for a one-off session.

3 Likes

Thanks for providing useful Date() methods.

I solved the problem Code Challenges: Javascript Fundamentals with if block, however when i try to solve the problem with switch block it gives logical error. can you guide please:

const howOld = (age, year) => {

  //calculating current year.
  let currentDate = new Date();
  let currentYear = currentDate.getFullYear();
  
  //calculating difference in year
  const yearDifference = year - currentYear;
  const calculatedAge = age + yearDifference;
  
  switch (year) {
    case (calculatedAge > age):
      return `You will be ${calculatedAge} in the year ${year}`;
      break;
    case (calculatedAge < 0 ):
      return `The year ${year} was ${-calculatedAge} year before you were born`;
      break;
    default:
      return `You were ${calculatedAge} in the year ${year}`;
      break;
  }
}
console.log(howOld(25, 2024));

It showing following output:

You **were** 30 in the year 2024

But when I do solve the problem with if block it shows:

You **will be** 30 in the year 2024

The case expression should relate to the switch argument.

Aside

break after return is unreachable. All three may be removed.

2 Likes

Hi guys, as far as I can tell my code still works but I can getting a “failed” from codecademy. I am not sure what is wrong. I don’t have any code errors and it prints what I want. Thanks!

// Write your function here:
const howOld = (age, year) => {
let currentDate = new Date();
let currentYear = currentDate.getFullYear();

const calculateBirthYear = currentYear - age;
const calculateAge = year - calculateBirthYear;
const yearDiff = calculateBirthYear - year

if (year > currentYear) {
console.log(You will be ${calculateAge} in the year ${year})
} else if (year < calculateBirthYear) {
console.log(The year ${year} was ${yearDiff} years before you were born)
} else {
console.log(You were ${calculateAge} in the year ${year})
}

}

// Once your function is written, write function calls to test your code!
howOld(28,1995)

Hi Design,

Have you tried it using the return keyword rather than console.log after each condition?

Best of luck.
P

Is it not possible to get current year based on Date without declaring the variable first?
Similar to what we do with Math.floor(math.random()); like so:

  1. const currentYear = getFullYear(Date());
    or
  2. const currentYear = getFullYear.Date();

I’ve tried both with no luck but I’m not sure I understand why. What is the difference between 1 and 2 above?

Date is a special object, a constructor. We create instances with the new operator.

    d =  new Date()
    console.log(d.getFullYear())    //  2019
1 Like

I see, like in the solution code. I was thinking it was possible to save one line of code but I suppose not.

1 Like

We can get just the year from a transient Date instance…

const currentYear = new Date().getFullYear()

then we don’t have an unused Date object taking up memory.

1 Like

Ah, that’s what I was I was going for. Thanks.

1 Like

Hi this code is showing this error

If the year passed in was before the person was born, the function should return: ‘The year [year passed in] was [calculated number of years prior to their birth] years before you were born’

Can you help me?

// Write your function here:

function howOld(age,year){
  let currentDate = new Date();
  let theCurrentYear = currentDate.getFullYear();

  const  yearDifference = year - theCurrentYear;
  const newAge = age + yearDifference;
  const ageDifference = age-newAge;

  if(newAge < 0){
    return `The year ${year} was ${ageDifference} years before you were born`
  }else if(newAge > age){
    return `You will be ${newAge} in the year ${year}`;
  }else if(newAge < age){
     return `You were ${newAge} in the year ${year}`;
  }else{
    return `Input future or past year `
  }
}



// Once your function is written, write function calls to test your code!
console.log(howOld(24,1990));
function howOld(age, year) {
  let currentDate = new Date();
  let theCurrentYear = currentDate.getFullYear();

  const yearDifference = year - theCurrentYear;
  const newAge = age + yearDifference;

  if (newAge < 0) {
    return `The year ${year} was ${Math.abs(newAge)} years before you were born`;
  } else if (newAge > age) {
    return `You will be ${newAge} in the year ${year}`;
  } else if (newAge < age) {
    return `You were ${newAge} in the year ${year}`;
  } else {
    return `Input future or past year `;
  }
}

console.log(howOld(32, 2030));

your const ageDifference = age-newAge; is incorrectly calculated if the person was born before that year. Your const newAge = age + yearDifference; is perfect to use because it will either be a positive or a negative. So when it is a negative you can just use the Math.abs() method to convert it to a positive for the first condition of your if statement

2 Likes

Thank you @hystericalmisfit . This was really understanding .

I believe that your problem is that you are using a the console.log function inside your howOld function when what you should be doing is using return to get the value back. When you initialized the function you did so by calling it with the line “howOld(28, 1995)” this means it is expecting a value to be returned but console.log is not defined so you get the failed message. Remove the console.log and replace it with a simple return, that will fix the problem.

1 Like

Hi there,
I made this solution and it’s works. but the “next” bottom still not allow me to the next challange.
Would you like to review this one:

const howOld = (age, year) => {
const yearDifference = year - 2020;
const newAge = age + yearDifference;
const yearBirth = 2020-age;
const beforeBirth = yearBirth - year
if(year>2020) {
return You will be ${newAge} in the year ${year}
}else if (year<1990) {
return The year ${year} was ${beforeBirth} years before you were born
} else if (year<2020) {
return You were ${newAge} in the year ${year}
}
}