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(
this.getUTCFullYear(),
this.getUTCMonth(),
this.getUTCDate(),
this.getUTCHours(),
this.getUTCMinutes(),
this.getUTCSeconds()
).getTime();
}
It just seems a little convoluted to me. And I am not so sure about performance either.
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.)
Note that
getTime()returns milliseconds, not plain seconds.For a UTC/Unix timestamp, the following should suffice:
It will factor the current timezone offset into the result. For a string representation, David Ellis’ answer works.
To clarify:
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):
Also note that
getUTCDate()cannot be substituted forgetUTCDay(). This is becausegetUTCDate()returns the day of the month; whereas,getUTCDay()returns the day of the week.