Can I find the current date using JS?


#1

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}`);

#2

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.