How do I get a UTC Timestamp in JavaScript?

2019-01-01 07:17发布

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.

15条回答
余生请多指教
2楼-- · 2019-01-01 07:24

This will return the timestamp in UTC:

var utc = new Date(new Date().toUTCString()).getTime();

查看更多
初与友歌
3楼-- · 2019-01-01 07:26

If you want a one liner, The UTC Unix Timestamp can be created in JavaScript as:

var currentUnixTimestap = ~~(+new Date() / 1000);

This will take in account the timezone of the system. It is basically time elapsed in Seconds since epoch.

How it works:

  • Create date object : new Date().
  • Convert to timestamp by adding unary + before object creation to convert it to timestamp integer. : +new Date().
  • Convert milliseconds to seconds: +new Date() / 1000
  • Use double tildes to round off the value to integer. : ~~(+new Date())
查看更多
人间绝色
4楼-- · 2019-01-01 07:28

Yeah, you don't need to do that much; assuming I understand you correctly, you just want the toUTCString method.

var UTCstring = (new Date()).toUTCString();

console.log('UTCstring', UTCstring);
  

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.

查看更多
栀子花@的思念
5楼-- · 2019-01-01 07:28

I use the following:

Date.prototype.getUTCTime = function(){ 
  return this.getTime()-(this.getTimezoneOffset()*60000); 
};

Once defined this method you can do:

var utcTime = new Date().getUTCTime();
查看更多
情到深处是孤独
6楼-- · 2019-01-01 07:28

I am amazed at how complex this question has become.

These are all identical, and their integer values all === EPOCH time :D

console.log((new Date()).getTime() / 1000, new Date().valueOf() / 1000, (new Date() - new Date().getTimezoneOffset() * 60 * 1000) / 1000);

Do not believe me, checkout: http://www.epochconverter.com/

查看更多
临风纵饮
7楼-- · 2019-01-01 07:29

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 to new Date():

new Date()
// Wed Oct 11 2017 11:34:33 GMT+0200 (CEST)

new Date(new Date().toUTCString().slice(0, -3))
// Wed Oct 11 2017 09:34:33 GMT+0200 (CEST)
查看更多
登录 后发表回答