Javascript Unixtime

Just a note of how to get Unixtime in Javascipt.

var date_obj    = new Date;
var unixtime_ms = date_obj.getTime();
var unixtime    = parseInt(unixtime_ms / 1000);

Also a Javascript Unixtime conversion utility.

Leave A Reply - 11 Replies
J 2009-01-25 01:22pm - No Email - Logged IP:

Thanks for this snippet. You saved me a lot of time.

michael 2009-02-15 10:08am - No Email - Logged IP:

yeah thx mate

Andy Moore 2009-10-16 09:16am - No Email - Logged IP:

Brilliant, thanks. Just what I was looking for.

AC 2010-01-12 11:13am - No Email - Logged IP:

Great little script. Thanks for sharing

Xander 2010-05-03 02:42am - No Email - Logged IP:

Great example ! keep it simple and everyone understand

Kelson 2010-09-12 04:09am - No Email - Logged IP:

thx, exactly what I need.

Andrew 2010-09-23 06:29am - No Email - Logged IP:

Use multiplication over division, it's much faster. Also, Math.Floor is faster than parseInt var unixtime = Math.Floor(unixtime_ms.valueOf() * 0.001);

Ian 2010-12-11 03:41pm - No Email - Logged IP:

Use the optimizations Andrew gave. Plus, faster still than Math.floor is:

var unixtime = (new Date().getTime() * 0.001)|0;

Because it removes the extra namespace lookup and function call (see Ecmascript spec 11.10 - the behavior is explicitly specified).

Ian 2010-12-11 03:44pm - No Email - Logged IP:

Also, valueOf (as per Andrew's comment) is slightly faster than getTime:

var unixtime = (new Date().valueOf() * 0.001)|0;

soupKitchen 2012-09-06 03:49pm - No Email - Logged IP:

Thanks man! Saved me TONS(!!!) of time.

ximik777 2014-06-11 06:42am - No Email - Logged IP:

parseInt(+new Date() / 1000);

All content licensed under the Creative Commons License