Merc Merc - 2 years ago 128
Javascript Question

How do I get a UTC Timestamp in JavaScript?

While writing a web application, it makes sense to store (server side) all datetimes in the DB as UTC timestamps.

I was astonished when I noticed that you couldn't natively do much in terms of Timezone manipulation in Javascript.

I extended the Date object a little. Does this function make sense? Basically, every time I send anything to the server, it's going to be a timestamp formatted with this function...

Can you see any major problems here? Or maybe a solution from a different angle?

Date.prototype.getUTCTime = function(){
return new Date(

It just seems a little convoluted to me. And I am not so sure about performance either...



Answer Source
  1. Dates constructed that way use the local timezone, making the constructed date incorrect. To set the timezone of a certain date object is to construct it from a date string that includes the timezone. (I had problems getting that to work in an older Android browser.)

  2. Note that getTime() returns milliseconds, not plain seconds.

For a UTC/Unix timestamp, the following should suffice:

Math.floor((new Date()).getTime() / 1000)

It will factor the current timezone offset into the result. For a string representation, David Ellis' answer works.

To clarify:

new Date(Y, M, D, h, m, s)

That input is treated as local time. If UTC time is passed in, the results will differ. Observe (I'm in GMT +02:00 right now, and it's 07:50):

> var d1 = new Date();
> d1.toUTCString();
"Sun, 18 Mar 2012 05:50:34 GMT" // two hours less than my local time
> Math.floor(d1.getTime()/ 1000)

> var d2 = new Date( d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate(), d1.getUTCHours(), d1.getUTCMinutes(), d1.getUTCSeconds() );
> d2.toUTCString();
"Sun, 18 Mar 2012 03:50:34 GMT" // four hours less than my local time, and two hours less than the original time - because my GMT+2 input was interpreted as GMT+0!
> Math.floor(d2.getTime()/ 1000)

Also note that getUTCDate() cannot be substituted for getUTCDay(). This is because getUTCDate() returns the day of the month; whereas, getUTCDay() returns the day of the week.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download