tags:

views:

3677

answers:

3

is it possible to create a jQuery function so that it gets current date and time? I've been looking around documentation but haven't found anything so far...

+3  A: 

It's plain javascript:

new Date()
nickf
+7  A: 

@nickf's correct. However, to be a little more precise:

// if you try to print it, it will return something like:
// Sat Mar 21 2009 20:13:07 GMT-0400 (Eastern Daylight Time)
// This time comes from the user's machine.
var myDate = new Date();

So if you want to display it as mm/dd/yyyy, you would do this:

var displayDate = (myDate.getMonth()+1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear();

Check out the full reference of the Date object. Unfortunately it is not nearly as nice to print out various formats as it is with other server-side languages. For this reason there-are-many-functions available in the wild.

Paolo Bergantino
you indicated format mm/dd/yyyy, but displayDate will be in dd/mm/yyyy format...very minor discrepancy to a nice answer
CarolinaJay65
Ah, yes. Thank you. Fixed.
Paolo Bergantino
+1  A: 

You don't need jquery to do that, just javascript. For example, you can do a timer using this:

<body onload="clock();">

<script type="text/javascript">
function clock() {
   var now = new Date();
   var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
   document.getElementById('clockDiv').innerHTML=outStr;
   setTimeout('clock()',1000);
}
clock();
</script>   

<div id="clockDiv"></div>

</body>

You can view a complete reference here: http://www.hunlock.com/blogs/Javascript_Dates-The_Complete_Reference

eKek0