Small JavaScript’s trick about Date object.
June 18, 2009 – 4:08 pmToday I’ve found one more trick about JavaScript and I think it will be interesting for someone else.
So, how do you usually get timestamp value with JavaScript?
I used the following code:
<script type=”text/javascript”>
var timestamp = Math.round(new Date().getTime()/1000);
</script>
As you might know Firefox has its own function to get timestamp named now, so you can do static call like this:
<script type=”text/javascript”>
var timestamp = Math.round(Date.now()/1000);
</script>
In this case you aren’t creating a new Date object. That is a good point.
But, what can we do for the rest browsers? Of course we can use known construction (see above). However there is one more possible constraction:
<script type=”text/javascript”>
var timestamp = Math.round(+new Date/1000);
</script>
As we see this construction is shorter. How does it work?
When script calls +new Date the script creates new Date object and makes a call to valueOf method of Date object.
In turn the valueOf method returns the number of milliseconds since midnight 01 January, 1970 UTC, so it is an equivalent to the getTime method.
I’ve check it with performance and they work identical.
Here is updated variant:
<script type=”text/javascript”>
function timestamp()
{
return Math.round(
(Date.now && Date.now() || +new Date)/1000
);
}
</script>
Enjoy it!

