I have a epoch/unix timestamp which I have, which I get after running the journalctl -o json-pretty -f
command. So I get my "__REALTIME_TIMESTAMP" : "1576681153604871"
value from a given log. I want to convert this to an ISOString format, so I use the below code
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();
I get the output as below
"2019-12-18T14:25:49.605Z"
I wish to even display the microsecond part in this something like
"2019-12-18T14:25:49.605762Z"
but myDate.toISOString()
doesn't work properly if I don't convert the epoch to milliseconds.
I dont know if time % 1000
is the right way, to extract the microsecond part and then append it to get the desired output .
So is there a way to get the output in microsecond format ?
So is there a way to get the output in microsecond format ?
Not using built–in methods. You can add the microsecond part yourself though. It's best to use string methods to get the digits to preserve leading zeros:
// 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);
It might be better to replace the entire decimal part though, just in case some future implementation decides to add more digits after the decimal place.
let tv = 1576681153064071;
let isoDate = new Date(tv/1e3).toISOString().replace(/\d+Z$/, String(tv).slice(-6) + 'Z');
console.log(isoDate);