Getting current date is commonly used operation when write javascript code. In this article, we will look at how to get current date, year, month in javascript.
It will also cover how to get current time, that is, hour, minute, second and millisecond in javascript.

Date Object
Javascript provides a Date object which is used to get date and time. It is created by its constructor using new operator as shown below

let date = new Date();

If this is printed, you will get current moment which shows day, date, month, time along with timezone as shown below

Sat Dec 19 2020 18:51:20 GMT+0530 (India Standard Time)

This is often not of much use. We will now look at how to get date(year, month, day).
Current Date
Date object provides methods getDate(), getMonth() and getFullYear() to get the current values for all these fields. Example,

let date = new Date();
document.write("Today's date: ",date.getDate(),"</br>");
document.write("Today's month: ",date.getMonth(),"</br>");
document.write("Today's year: ",date.getFullYear(),"</br>");

This prints

Today’s date: 19
Today’s month: 11
Today’s year: 2020

Note that Date counts months from 0 to 11. So, to get the correct month, add 1 to the return value of getMonth().

Now, you can construct the date in required format such as dd-MM-YYYY or dd/MM/YYYY as shown below,

let date = new Date(); 
let dateFormat = date.getDate() + '/' + (date.getMonth() + 1)
                  + '/' + date.getFullYear();
document.write("Current Date in dd/MM/YYYY: ",dateFormat,"</br>"); 
dateFormat = date.getDate() + '-' + (date.getMonth() + 1)
                + '-' + date.getFullYear();
document.write("Current Date in dd-MM-YYYY: ",dateFormat,"</br>");

Output will be

Current Date in dd/MM/YYYY: 19/12/2020
Current Date in dd-MM-YYYY: 19-12-2020

Current Time
Date object provides methods getHours(), getMinutes(), getSeconds(), getMilliseconds() to get the corresponding time components.
These methods can be used to get the current time in desired format. Example,

let date = new Date(); 
let time = date.getHours() + ':' + date.getMinutes() 
           + ':' + date.getMinutes() + ':' + date.getMilliseconds();
document.write("Current Time in hh:mm:ss.S: ",time);

This prints

Current Time in hh:mm:ss.S: 19:19:19:502

Hope the article was useful.

Liked the article ? Spread the word...