JavaScript

How to Display the Current Date and Time in Javascript

In this tutorial, we are going to see how to display the date and time in Javascript. In Javascript, the date and time are handled with the Date object.
 

Display the Current Date and Time in Javascript

The Date object is an object natively included in JavaScript that stores the current date and time given by the browser.

var today = new Date();
 
The Date object has several methods to retrieve the date and time:

Method
Example
toString(): will return a string representation of the Date object.
console.log(today.toString());

Output:

Fri Sep 20 2019 19:38:22 GMT+0200
getDate(): will return the day of the month.
console.log(today.getDate());

Output:

25
getMonth(): will return the month.
console.log(today.getMonth());

Output:

12
getFullYear(): will return the year.
console.log(today.getFullYear());

Output:

2020
getHours(): will return the hours.
console.log(dt.getHours());

Output:

07
getMinutes(): will return the minutes
console.log(dt.getMinutes());

Output:

59
getSeconds(): will return the seconds
console.log(dt.getSeconds());

Output:

30

 

Display the current date in JavaScript
var d = new Date();
var date = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
console.log(date);

Output:

2020-1-20
 

Display the current time in JavaScript
var d = new Date();
var hours = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
console.log(hours);

Output:

19:59:44

 

Display the current date and time in JavaScript

You can simply combine the output of the above JavaScript code into a variable like below:

var d = new Date();
var date = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
var hours = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
var fullDate = date+' '+hours;
console.log(fullDate);

Output:

2020-1-20 19:59:44
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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