Current unix time / stamp :


Unix time in JavaScript

Getting the Unix timestamp in JavaScript is not magic, in fact it can be done with just two lines of code. Start by initializing a date object, like so:

var foo = new Date;

Now it is just a question of using the getTime() function on the date object we made, but since getTime() returns milliseconds rather than seconds, we have to divide the result by 1000 as seen below:

var unixtime = parseInt(foo.getTime() / 1000);

And that's how to get the unix timestamp in Javascript.

To convert a Unix timestamp to a human readable date in JavaScript, we must again create a date object, but this time we pass it a parameter of: Unix timestamp multiplied by 1000. The reason for the multiplication is that JavaScript Date works in milliseconds as shown earlier.

var unixtime_to_date = new Date(unixtime*1000);

unixtime_to_date can now be used. If you just print it out, it will state the date of the Unix timestamp you gave it in a format like this: Sat Oct 24 2009 01:23:45 GMT+0200. However, you can also use functions on it to return a more specific value, for example unixtime_to_date.getHours() or unixtime_to_date.getMinutes().