How To Get Current Date In JavaScript

How to get current date in JavaScript

In this short post, we’re going to understand how we can get current date in JavaScript.

The following code will log the current date in the console in mm/dd/yyyy format.

const now = new Date();
let day = now.getDate();
let month = now.getMonth() + 1;
let year = now.getFullYear();

if (day < 10) {
    day = '0' + day
} 

if (month < 10) {
    month = '0' + month
} 

const today = month + '/' + day + '/' + year;
console.log(today);

Now, let’s go line by line and understand what exactly is happening in this code.

const now = new Date();
let day = now.getDate()();
let month = now.getMonth() + 1;
let year = now.getFullYear();

At line one, we’re creating a new instance of the date object. And in the next three lines, we’re extracting the day, month and year.

  • getDate – returns the current date (1-31).
  • getMonth – returns the current month (0-11). Values start at zero that represents January and ends at eleven that represents December. Hence we’re adding one to month.
  • getFullYear – returns current year in four digit format e.g. 2019.
if(day < 10) {
    day = '0' + day
} 

if(month < 10) {
    month = '0' + month
} 

Next, we’re adding zero at the beginning of day and month if they are single digit numbers.

const today = month + '/' + day + '/' + year;
console.log(today);

And at the last two lines we’re simply concatenating the day, month and year in mm/dd/yyyy format and logging it to the console.

Must Read: JavaScript ES6 – What are Template Literals

Thank you for reading. I hope you found this post useful. In case you’ve any query or feedback feel free to drop a comment on this post.

For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

2 thoughts on “How To Get Current Date In JavaScript”

Leave a Reply

Your email address will not be published. Required fields are marked *