当前时间和 3500 毫秒之前的 Javascript UTC 时间戳

请有人告诉我如何做到这一点。我已经尝试了我找到的所有方法。没有任何工作。我不想进口任何东西。我只需要当前时间戳和 3500 毫秒之前。这是用于 API 调用


这是我到目前为止的位置:


var current_date = new Date().toLocaleString("en-US", {timeZone: "Europe/London"});



var start_date = new Date();

start_date.setMinutes(start_date.getMinutes() - 3); // timestamp

start_date = new Date(start_date).getTime(); // Date object


FFIVE
浏览 218回答 2
2回答

翻阅古今

我不知道您的 API 调用是否采用 unix 时间戳或 ISO-8601 字符串(或其他日期格式)。您可以使用本机 JavaScript 日期对象轻松获取 UTC 时间。Date.getTime()将始终为我们提供从 unix 纪元开始的时间(以毫秒为单位),这与我们调用它的时区无关。如果您需要以秒为单位的 unix 时间戳,您可以除以 1000。同样Date.toISOString()将以ISO-8601格式为我们提供当前的 UTC 时间,因此这也是明确的。向日期添加偏移量(以毫秒为单位)很容易,只需将您的偏移量添加/减去到 unix 纪元偏移量(返回 Date.getTime()),然后传递给 Date 构造函数以获取您的偏移日期。如果您希望发送 US / GB 等格式字符串,我建议您使用Date.toLocaleString,如果您采用这种方法,则可以使用“UTC”作为时区。如果您想创建自定义 UTC 时间字符串,您始终可以使用Date.getUTCFullYear、 Date.getUTCMonth、Date.getUTCDate等并结合起来创建您的日期字符串。const locale = "en-us";const currentTimeUnix = new Date().getTime();const currentDate = new Date(currentTimeUnix );console.log(`Current UTC time (unix, ms): ${currentTimeUnix}`);console.log(`Current UTC time (unix, sec): ${Math.round(currentTimeUnix/1000)}`);console.log(`Current UTC time (ISO-8601): ${currentDate.toISOString()}`);console.log(`Current UTC time (locale format):`, currentDate.toLocaleString(locale, { timeZone: 'UTC' }));const offsetMilliseconds = 3500;// Subtract the offset from the current timeconst offsetTimeUnix = currentTimeUnix - offsetMilliseconds;const offsetDate = new Date(offsetTimeUnix);console.log(`\nResults after subtracting offset (${offsetMilliseconds}ms):`);console.log(`Offset UTC time (unix, ms): ${offsetTimeUnix}`);console.log(`Offset UTC time (unix, sec): ${Math.round(offsetTimeUnix / 1000)}`);console.log(`Offset UTC time (ISO-8601): ${offsetDate.toISOString()}`);console.log(`Offset UTC time (locale format):`, offsetDate.toLocaleString(locale, { timeZone: 'UTC' }));// NB: Month is zero-based in JavaScriptconst customTimestamp = `${offsetDate.getUTCFullYear()}-${offsetDate.getUTCMonth() + 1}-${offsetDate.getUTCDate()} ${offsetDate.getUTCHours()}:${offsetDate.getUTCMinutes()}:${offsetDate.getUTCSeconds()}`;console.log(`Offset UTC time (custom format):`, customTimestamp);

潇潇雨雨

这很容易做到。来自Date.prototype.getTimegetTime()方法返回自 Unix 纪元以来的毫秒数* 。* JavaScript 使用毫秒作为度量单位,而 Unix 时间以秒为单位。getTime() 始终使用 UTC 表示时间。例如,一个时区的客户端浏览器,getTime() 将与任何其他时区的客户端浏览器相同。由于 JS 使用毫秒时间戳,只需获取当前时间的时间戳(始终为 UTC),然后从中减去任何毫秒数。let currentTimestamp = new Date().getTime();let threePointFiveSecondsAgo = currentTimestamp - 3500;// convert timestamp back in to a date.let pastDate = new Date(threePointFiveSecondsAgo);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript