Categories
JavaScript Answers

How to Get the Current Date and Time in JavaScript?

Spread the love

Using Date Methods

We can use native JavaScript date methods to get parts of a date-time.

For instance, we can write:

const currentDate = new Date();  
const dateTime = currentDate.getDate() + "/" +  
  (currentDate.getMonth() + 1) + "/" +  
  currentDate.getFullYear() + " @ " +  
  currentDate.getHours() + ":" +  
  currentDate.getMinutes() + ":" +  
  currentDate.getSeconds();

We call the getDate method to get the day of the month.

getMonth returns the month of the year from 0 to 12.

So we’ve to add 1 to get a human-readable month number.

getFullYear returns the 4 digit year number.

getHours returns the hours of the day.

getMinutes returns the minutes of the hour.

getSeconds returns the seconds of the minute.

The toLocaleString Method

We can use the date objects’ toLocaleString method to return a human-readable date string.

For instance, we can write:

const dateTime = new Date().toLocaleString();  
console.log(dateTime)

Then we get something like:

2/24/2021, 3:04:27 PM

as a result.

The toLocaleDateString Method

Another method we can use to return a human-readable date string is the toLocaleDateString method.

For instance, we can write:

const dateTime = new Date().toLocaleDateString();  
console.log(dateTime)

to call the method.

And we get:

2/24/2021

as a result.

The toLocaleTimeString Method

Another method we can use to return a human-readable date string is the toLocaleTimeString method.

It takes a locale string and an object with options we want to set for returns the date string as the second argument.

For example, we can write:

const dateTime = new Date().toLocaleTimeString('en-US', {  
  hour12: false,  
  hour: "numeric",  
  minute: "numeric"  
});  
console.log(dateTime)

and we get something like:

15:06

from the console log.

hour12 set to false means we return a 24-hour date.

hour and minute are set th 'numeric' means we return the hour and minute as numbers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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