JavaScript new Date() 使用哪个时区?

What time zone does the JavaScript new Date() use?

我有一个 C# 应用程序,在 JSON 中 return 身份验证令牌的到期日期如下:

"expirationDate":"Fri, 27 Mar 2015 09:12:45 GMT"

在我的 TypeScript 中,我检查这里的日期是否仍然有效:

isAuthenticationExpired = (expirationDate: string): boolean => {
    var now = new Date().valueOf();
    var exp: any = Date.parse(expirationDate).valueOf();
    return exp - now <= 0;
};

我想知道 new Date() 在 return 约会时使用什么时区?

默认情况下,JS 将使用您的浏览器时区,但如果您想更改显示,您可以使用 toString() 函数 ;)

var d1=new Date();
d1.toString('yyyy-MM-dd');       //returns "2015-03-27" in IE, but not FF or Chrome
d1.toString('dddd, MMMM ,yyyy')  //returns "Friday, March 27,2015" in IE, but not FF or Chrome

What time zone does the Javascript new Date() use?

Date 对象使用自大纪元(1970 年 1 月 1 日格林威治标准时间午夜)以来的毫秒数。他们有像 getDaygetMonth 这样的方法,这些方法使用 JavaScript 引擎的本地时区,还有像 getUTCDaygetUTCMonth 这样使用 UTC 的函数(松散地,格林威治标准时间)。

如果您要解析字符串,则需要确保该字符串的格式 Date 知道如何解析。规范中唯一 定义的 格式是 a simplified derivative of ISO-8601,但它仅在 ES5 中添加,并且他们在规范中错误地说明了如果没有时区指示器应该发生什么字符串,因此您需要确保其上始终有一个时区指示器(目前,ES6 将修复它,最终引擎将可靠地使用 ES6 行为)。这些字符串看起来像这样:

"2015-03-27T09:32:54.427Z"

您可以使用 toISOString 方法生成该格式。

JavaScript 将使用客户端的本地时间,但它也有 UTC / GMT 方法。以下来自 Mozilla:

The JavaScript Date object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.

虽然可以使用 UTC 和本地时区访问日期和时间的方法,但日期和时间存储在本地时区中:

Note: It's important to keep in mind that the date and time is stored in the local time zone, and that the basic methods to fetch the date and time or its components all work in the local time zone as well.

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

正如其他人所说,JavaScript 使用客户端系统时间,但您可以从服务器时间创建日期对象,因此每个客户端都将获得相同的当前时间。

var date = new Date("<?php echo date("Y-m-d H:i:s");?>");

它将仅在页面加载时起作用。如果您想稍后检查日期是否仍然有效,则需要每隔几秒将当前日期与服务器日期同步一次。