javascript - 如何将 performance.now() 输出转换为 UTC 字符串?

标签 javascript datetime high-resolution-time performance.now

在我们的代码中,我们之前像这样计算事件之间的差异:

var beginTime = new Date();
// Do stuff
var endTime = new Date();
var duration = endTime.getTime() - beginTime.getTime();

console.log("Job began at " + beginTime.toUTCString()
            + " and took " + duration + " milliseconds.");

这会产生一个人类可读的字符串:

Job began at Thu Sep 28 2017 11:17:33 GMT-0500 (Central Daylight Time) and took 7000 milliseconds.

我们决定切换到 High Resolution Time通过使用更可靠的 performance.now()。但是,我们仍然希望能够包含一个人类可读的 UTC 时间字符串。

最初,我们试过这个:

var beginTime = performance.now();
// Do stuff
var endTime = performance.now();
var duration = endTime - beginTime;

console.log("Job began at " + new Date(beginTime).toUTCString() 
            + " and took " + duration + " seconds.");

我们发现持续时间是准确的,但是 new Date(performance.now()) 导致 UTC 值不准确(在撰写本文时,它提供了将近 50 年的日期过去)。

Job began at Wed Dec 31 1969 20:10:46 GMT-0600 (Central Standard Time) and took 7000 milliseconds.

是否有更好的方法将 performance.now() 的输出转换为准确的 UTC 字符串?它不必与 new Date().toUTCString() 的格式完全相同,但它应该是人类可读的。

最佳答案

我会这样做:

// mark the start time
performance.mark("start");

// ... 
//  later...
// ...
// mark the end time
performance.mark("end");

// create a measure called 'm' based on the two marks above
performance.measure("m", "start", "end");

// get the start mark, calculate its real-world timestamp using the time origin
var started = performance.getEntriesByName("start")[0];
var startedDt = new Date(performance.timing.navigationStart + started.startTime);

// get the measure we created above
var duration = performance.getEntriesByName("m")[0];
console.log(`job began on ${startedDt} and took ${duration.duration/1000.0} seconds`);

performance.clearMarks();

首先,标记持续时间测量的开始和结束时间。其次,创建持续时间测量。

稍后,您将获得开始和结束标记,通过将时间原点与开始标记的时间戳相结合来计算开始日期。最后,清除标记。

获取开始标记并不是绝对必要的...您还可以根据度量 m 计算真实世界的开始时间戳,它也有一个 startTime。我使用了开始标记,但两者都有效。

换句话说,你也可以这样做:

// get the measure we created above
var duration = performance.getEntriesByName("m")[0];
var startedDt = new Date(performance.timing.navigationStart + duration.startTime);

console.log(`job began on ${startedDt} and took ${duration.duration/1000.0} seconds`);

关于javascript - 如何将 performance.now() 输出转换为 UTC 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46474421/

相关文章:

php - 使用OAuth验证应用程序以访问融合表

python - 获取纳秒级精度的文件修改时间

javascript - tinyMce 绑定(bind) focusin/focusout 事件?

javascript - AmCharts 4 "animateData is not a function"或 'How to reanimate chart new data' ?

javascript - 我应该学习 Flash/Flex/ActionScript 还是 HTML/CSS/JS ("HTML5")?

windows - 如何获取毫秒分辨率的 Windows 系统时间?

php - 动态检查 mySQL 数据库以查看当前时间是否已超过存储在数据库中的日期时间

mysql不在日期时间中存储微秒,但在where条件下使用?

javascript - ".000Z"的 "yyyy-mm-ddT00:00:00.000Z"是什么意思?