从 unix 时间戳以微秒为单位获取 ISOString

Get ISOString in microseconds from unix timestamp

我有一个 epoch/unix 时间戳,这是我在 运行 journalctl -o json-pretty -f 命令之后得到的。所以我从给定的日志中得到我的 "__REALTIME_TIMESTAMP" : "1576681153604871" 值。我想将其转换为 ISOString 格式,所以我使用以下代码

var result;
time = parseInt(time);
var msec = time/1000; // convert __REALTIME_TIMESTAMP to milliseconds from microseconds
var myDate = new Date(msec);
var isoDate = myDate.toISOString();

我得到如下输出

"2019-12-18T14:25:49.605Z"

我什至希望在其中显示微秒部分,例如

"2019-12-18T14:25:49.605762Z"

但如果我不将纪元转换为毫秒,myDate.toISOString() 将无法正常工作。

我不知道 time % 1000 提取微秒部分然后附加它以获得所需输出的方法是否正确。

那么有没有办法获得微秒格式的输出?

So is there a way to get the output in microsecond format ?

不使用内置方法。不过,您可以自己添加微秒部分。最好使用字符串方法来获取保留前导零的数字:

// Time value in microseconds
let tv = 1576681153064071;
// Get millisecond part
let msec = tv/1000;
// Get microsecond part - keep leading zeros
let μsec = String(tv).slice(-3);
// Get ISO 8601 timestamp
let isoDate = new Date(msec).toISOString();
// Add in microseconds
let isoDatePlus = isoDate.replace('Z', μsec + 'Z');

console.log(isoDatePlus);

虽然替换整个小数部分可能会更好,以防万一将来的某些实施决定在小数位后添加更多数字。

let tv = 1576681153064071;
let isoDate = new Date(tv/1e3).toISOString().replace(/\d+Z$/, String(tv).slice(-6) + 'Z');

console.log(isoDate);