How to Get the Current Date and Time in JavaScript

The JavaScript Date prototype object creates a new method that will return the current date and time. In this snippet, we will explain how you can accomplish your task step by step.

How to Get the Current Date

The first thing is using the Date() function to create an object in JavaScript:

let currentDate = new Date()

Then you should use the following script to get the current date in the “m-d-y” format. You can change the format.

let currentDate = new Date();
let cDay = currentDate.getDate()
let cMonth = currentDate.getMonth() + 1
let cYear = currentDate.getFullYear()
  • getDate() – Provides the day of the month values 1-31.
  • getMonth() – Provides the current month with 0-11 values (0 for Jan and 11 for Dec). You should add +1 to get result.
  • getFullYear() – Provides the current year.

Here’s the full code:

let currentDate = new Date();
let cDay = currentDate.getDate();
let cMonth = currentDate.getMonth() + 1;
let cYear = currentDate.getFullYear();
console.log("<b>" + cDay + "/" + cMonth + "/" + cYear + "</b>");

How to Get the Current Time

The Date object is used to get the current time in JavaScript.

Here is how you can get the time in “h:i:s” format. You can change the format whatever you wish.

let currentDate = new Date();
let time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
  • getHours() – Provides the current hour from 0 to 23.
  • getMinutes() – Provides the current minutes from 0 to 59.
  • getSeconds() – Provides the current seconds from 0 to 59.

To combine date and time in a single variable run the following:

let current = new Date();
let cDate = current.getFullYear() + '-' + (current.getMonth() + 1) + '-' + current.getDate();
let cTime = current.getHours() + ":" + current.getMinutes() + ":" + current.getSeconds();
let dateTime = cDate + ' ' + cTime;

Date and Time

JavaScript provides a built-in object Date for handling operations related to all the date and time. You can use it for displaying the current date and time, creating a calendar, building a timer, etc.

When a Date object is created, it allows a number of methods to work on it. Most of them will enable you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object.

Do you find this helpful?

Related articles