Javascript – How to get current Date and Time?

  • by

How to get Current DateTime in JavaScript?

The “new Date()” method in javascript will by default show date and time string with browser’s current Time zone.
Example:

var date = new Date();
Output:

To convert the above Date time format we can use Date.toDateString() function.
Example:

var date = (new Date()).toDateString()
Output:

Getting Date and Time in Simplified form from Javascript:

Months in Javascript starts from 0. January is 0 and February is 1.
To get only Date using Javascript, use:

var date = new Date();
date.getDate()+'/' + (date.getMonth()+1)+'/'+date.getFullYear();
Output:

To get only Time using Javascript, use:

var date = new Date();
date.getHours()+':'+date.getMinutes()+':'+date.getSeconds()
Output:

Date in javascript is stored in Milliseconds format from 1st Jan 1970 00:00:00 UTC. When we call date.getTime()
Example:

var date = new Date().getTime();
Output:

To get Date and Time in Local format (system DateTime format) using Javascript, use:

var date = new Date().toLocaleString();
Output:

Usage

Index.html:

<html>
<head>
<title>Current DateTime in Javascript</title>

<style>
body
{
padding: 5px;
font-family: Arial, Helvetica, sans-serif;
}
</style>
</head>
<body>
<div>
<p id="pDateTime"></p>
<p id="pSimplifiedDate"></p>
<p id="pDate"></p>
<p id="pTime"></p>
<p id="pMilliseconds"></p>
<p id="pLocal"></p>
</div>
</body>

<script>
var date = new Date();
document.getElementById("pDateTime").innerHTML = date;
document.getElementById("pSimplifiedDate").innerHTML = (new Date()).toDateString();
document.getElementById("pDate").innerHTML = date.getDate()+'/' + (date.getMonth()+1)+'/'+date.getFullYear();
document.getElementById("pTime").innerHTML = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
document.getElementById("pMilliseconds").innerHTML = date.getTime();
document.getElementById("pLocal").innerHTML = date.toLocaleString();
</script>
</html>

VIEW SAMPLE

More how Javascipt:
How to Create a Digital Clock in Javascript.