Wednesday, 20 November 2013

Get current Date time in JQuery

Description:

  In this article, I am going to write JQuery 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 JQuery
  2. Get current UTC (Universal) Date Time in JQuery
  3. Get current Date in JQuery (without time part)

Get current local Date Time in JQuery

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 type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
function ShowLocalDate()
{
var dNow = new Date();
var localdate= (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
$('#currentDate').text(localdate)
}

</script>
</head>
<body>

<h1>Get current local Date in JQuery</h1>
<label id="currentDate">This is current local Date Time in JQuery</p>
<button type="button" onclick="ShowLocalDate()">Show Local DateTime</button>

</body>
</html> 


Get current UTC (Universal) Date Time in JQuery

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>

<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();
$('#currentDate').text(utcdate)
}

</script>
</head>
<body>

<h1>Get UTC DateTime in JQuery</h1>
<label id="currentDate">This is UTC DateTime in JQuery</p>
<button type="button" onclick="ShowUTCDate()">Show UTC DateTime</button>

</body>
</html>


Get current Date in JQuery (without time part)

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>

function ShowDate()
{
var dNow = new Date();
var utcdate= (dNow.getMonth()+ 1) + '/' + dNow.getDate() + '/' + dNow.getFullYear();
$('#currentDate').text(utcdate)
}

</script>
</head>
<body>

<h1>Get current Date in JQuery</h1>
<label id="currentDate">This is current Date in JQuery</p>
<button type="button" onclick="ShowDate()">Show current Date</button>

</body>
</html> 

Advertisements
Advertisements

3 comments:

  1. Awsome! thank you!

    ReplyDelete
  2. thank you for the simple code but I was wondering if I wanted to show date and time after loading not after clicking button ,so what code to write for this
    thanks in advance.

    ReplyDelete
    Replies
    1. Just use this code inside script tag


      window.onload = function() {
      ShowDate();
      }

      Delete