2 回答
TA贡献1780条经验 获得超5个赞
我不知道您的 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 time
const 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 JavaScript
const customTimestamp = `${offsetDate.getUTCFullYear()}-${offsetDate.getUTCMonth() + 1}-${offsetDate.getUTCDate()} ${offsetDate.getUTCHours()}:${offsetDate.getUTCMinutes()}:${offsetDate.getUTCSeconds()}`;
console.log(`Offset UTC time (custom format):`, customTimestamp);
TA贡献1833条经验 获得超4个赞
这很容易做到。
来自Date.prototype.getTime
getTime()方法返回自 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);
添加回答
举报
