在编写web应用程序时,将(服务器端)所有日期时间作为UTC时间戳存储在DB中是有意义的。

当我注意到在JavaScript中无法在时区操作方面原生做很多事情时,我感到很惊讶。

我稍微扩展了Date对象。这个函数有意义吗?基本上,每次我向服务器发送任何东西,它都将是一个用这个函数格式化的时间戳…

这里有什么主要问题吗?或者换个角度解决?

Date.prototype.getUTCTime = function(){ 
  return new Date(
    this.getUTCFullYear(),
    this.getUTCMonth(),
    this.getUTCDate(),
    this.getUTCHours(),
    this.getUTCMinutes(), 
    this.getUTCSeconds()
  ).getTime(); 
}

我只是觉得有点费解。我对表现也不是很确定。


当前回答

你也可以使用getTimezoneOffset和getTime,

x =新日期() var utccos = (x.getTime() + x. gettimezone胶印()*60*1000)/1000; 游戏机。log (UTCseconds”、“UTCseconds)

其他回答

如果你想要一行,UTC Unix时间戳可以在JavaScript中创建:

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

这将考虑到系统的时区。它基本上是以秒为单位的从epoch开始的时间。

工作原理:

创建日期对象:new date()。 通过在对象创建之前添加一元+将其转换为时间戳整数来转换为时间戳。: +new Date()。 将毫秒转换为秒:+new Date() / 1000 使用双波浪号将值舍入为整数。: ~~(+new Date())

你也可以使用getTimezoneOffset和getTime,

x =新日期() var utccos = (x.getTime() + x. gettimezone胶印()*60*1000)/1000; 游戏机。log (UTCseconds”、“UTCseconds)

我使用以下方法:

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

一旦定义了这个方法,你可以这样做:

var utcTime = new Date().getUTCTime();

我对这个问题变得如此复杂感到惊讶。

这些都是相同的,它们的整数值都=== EPOCH time:D

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

不相信我,结账: http://www.epochconverter.com/

我想说明的是,new Date(). gettime()实际上返回一个UTC值,因此它是一种非常有用的存储和管理日期的方式,不受本地化时间的影响。

换句话说,不要使用所有的UTC javascript函数。相反,只需使用Date.getTime()。

更多关于解释的信息在这里: 如果javascript "(new Date()). gettime()"从2个不同的时区运行。