获取 UTC 时间给我 NaN

Sam*_*Sam 5 javascript

为什么我使用以下代码得到 NaN?

var currentTime = new Date();
var utcTime = Date.UTC(currentTime);
console.log(utcTime);
Run Code Online (Sandbox Code Playgroud)

基本上,我想以 UTC 格式获取日期/时间值。获得它的最佳方法是什么?

Nin*_*rry 2

console.log(new Date().toUTCString());
Run Code Online (Sandbox Code Playgroud)

日期已在内部使用 UTC 时间。它们存储自 1970 年 1 月 1 日 0:00:00 UTC 以来的毫秒数。因此,仅当想要向用户显示值时,是否要显示本地时间或 UTC 时间才变得相关。


将 DateTime 值发送到 ASP.net API 时,有两种情况:

较新的 ASP.net 版本使用 JSON.net 进行 JSON 序列化。他们了解 ISO 8601 格式。所以,使用

var value = new Date().toISOString();
Run Code Online (Sandbox Code Playgroud)

较旧的 ASP.net 版本使用 Microsoft 特定格式,您可以像这样生成:

function makeMSDateFormat(date)
{
    return "\/Date(" + date.getTime() + ")\/";
}

var value = makeMSDateFormat(new Date());
Run Code Online (Sandbox Code Playgroud)

一些背景信息