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.
This will return the timestamp in UTC:
If you want a one liner, The UTC Unix Timestamp can be created in JavaScript as:
This will take in account the timezone of the system. It is basically time elapsed in Seconds since epoch.
How it works:
new Date()
.unary +
before object creation to convert it totimestamp integer
. :+new Date()
.+new Date() / 1000
~~(+new Date())
Yeah, you don't need to do that much; assuming I understand you correctly, you just want the
toUTCString
method.However, remember that the date values you get are based on the clock of the client's machine, not your server. If you need precise values for these dates (for instance, to properly order when this or that action was done relative to another user's action), you can't rely on the client-side date library, anyways, and you need to calculate the dates server-side based on when the client contacted you.
Remember as well that basically all of your client-side code can be modified by the client and malicious values returned instead, you can only guarantee the code on the server-side -- treat the client-side like a possible attacker.
I use the following:
Once defined this method you can do:
I am amazed at how complex this question has become.
These are all identical, and their integer values all === EPOCH time :D
Do not believe me, checkout: http://www.epochconverter.com/
Since
new Date().toUTCString()
returns a string like"Wed, 11 Oct 2017 09:24:41 GMT"
you can slice the last 3 characters and pass the sliced string tonew Date()
: