Get a UNIX timestamp with Javascript
Posted May 12th, 2009 in Javascript (Updated February 26th, 2011)
The Javascript Date object has a number of functions for working with dates and times. The getTime() method returns the millisecond representation of the Date object and this post shows how to convert this to a UNIX timestamp.
To convert the current date and time to a UNIX timestamp do the following:
var ts = Math.round((new Date()).getTime() / 1000);
getTime() returns milliseconds from the UNIX epoch, so divide it by 1000 to get the seconds representation. It is rounded using Math.round() to make it a whole number. The "ts" variable now has the UNIX timestamp for the current date and time relevent to the user's web browser.
Related posts:
- Get the number of days in a month with Javascript (Friday, December 18th 2009)
- Get the milliseconds with Javascript and measure time (Friday, May 15th 2009)
- Rounding numbers with Javascript (Tuesday, May 5th 2009)
- Pad a number with leading zeroes in Javascript - Improved (Friday, May 1st 2009)
- Format a date time in Javascript in database format (Friday, April 24th 2009)
- How to get the timezone offset with Javascript (Tuesday, February 17th 2009)

Comments
blog comments powered by Disqus