Thursday, 7 November 2013

Get current Date time in Javascript

Description:

  In this article, I am going to write javascript code examples to get current DateTime, UTC DateTime, current Date, current Date with specific date time format.

Summary:

  1. Get current local Date Time in Javascript
  2. Get current UTC (Universal) Date Time in Javascript
  3. Get current Date in Javascript (without time part)

Get current Date Time in Javascript

Note: We need add 1 with return value dNow.getMonth(), because the getMonth() method returns the month (from 0 to 11), January is 0, February is 1, and so on.
<html>
<head>
<script>
function ShowLocalDate()
{
var dNow = new Date();
var localdate= (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
document.getElementById("currentDate").innerHTML=localdate;
}
</script>
</head>
<body>
<h1>Get current local Date in Javascript</h1>
<label id="currentDate">This is current local Date Time in Javascript</p>
<button type="button" onclick="ShowLocalDate()">Show Local DateTime</button>
</body>
</html> 

Get current UTC (Universal) Date Time in Javascript

<html>
<head>
<script>
function ShowUTCDate()
{
var dNow = new Date();
var utc = new Date(dNow.getTime() + dNow.getTimezoneOffset() * 60000)
var utcdate= (utc.getMonth()+1) + '/' + utc.getDate() + '/' + utc.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes();
document.getElementById("currentDate").innerHTML=utcdate;
}
</script>
</head>
<body>
<h1>Get UTC DateTime in Javascript</h1>
<label id="currentDate">This is UTC DateTime in Javascript</p>
<button type="button" onclick="ShowUTCDate()">Show UTC DateTime</button>
</body>
</html> 

Get current Date in Javascript (without time part)

<html>
<head>
<script>
function ShowDate()
{
var dNow = new Date();
var utcdate= (dNow.getMonth()+ 1) + '/' + dNow.getDate() + '/' + dNow.getFullYear();
document.getElementById("currentDate").innerHTML=utcdate;
}
</script>
</head>
<body>
<h1>Get current Date in Javascript</h1>
<label id="currentDate">This is current Date in Javascript</p>
<button type="button" onclick="ShowDate()">Show current Date</button>
</body>
</html> 

Advertisements
Advertisements

2 comments:

  1. I'm really enjoying the theme/design of your website. Do you ever run into
    any internet browser compatibility issues? A number of my blog
    audience have complained about my blog not operating correctly in Explorer but looks great in Opera.
    Do you have any tips to help fix this problem?


    Here is my weblog todomariovargasllosacomes

    ReplyDelete