How To Get Current Date & Time In JavaScript?

JavaScript provides the Date data in order to work with date and time information. The Date object can be used to get the current date and time. In this tutorial, we will learn how to get the current date and time in different formats.

Get Current Date and Time

JavaScript provides the Date() method which creates the Date object. The Date object contains the date and time information with helpful functions. The Date object can be created like below.

var current = new Date();

Get Current Date

The Date object contains the date information and following methods can be used to print specific date information like year, month and day.

  • getFullYear() function returns the year in YYYY format like 2021.
  • getMonth() function returns the month in MM format like 0 or 11. The January is numbered as 0 like index number and in order to get real month number +1 should be added.
  • getDate() function returns the day of the month in DD format like 13.
var current = new Date();

var date = current.getFullYear()+'-'+(current.getMonth()+1)+'-'+current.getDate();

Get Current Time

The date object also provides the time information. Following functions are used to extract time information from the date object.

  • getHours() returns the current hour in HH format which is between 0-23.
  • getMinutes() returns current minutes in MM format which is between 0-59.
  • getSeconds() returns current seconds in SS format which is between 0-59.
var current = new Date();

var time = current.getHours()+'-'+current.getMinutes()+'-'+current.getSeconds();

Get Current Date and Time Both

Alternatively we can get both the current date and current time information into a single string like below. We will use the DateTime variable to put date and time information.

var current = new Date();

var date = current.getFullYear()+'-'+(current.getMonth()+1)+'-'+current.getDate(); 

var time = current.getHours()+'-'+current.getMinutes()+'-'+current.getSeconds();

var DateTime = date+' '+time;

Leave a Comment