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.

2 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.

2 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.

1 Like

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