2

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 ?

Abbas
  • 3,144
  • 2
  • 25
  • 45

2 Answers2

3

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);
RobG
  • 142,382
  • 31
  • 172
  • 209
0

Modifying @RobG's example, the technically correct and faster code would be

let tv = 1576681153064071;
let isoDate = new Date(tv/1e3).toISOString().slice(0, -4) + String(tv).slice(-6).padStart(6, '0') + 'Z';

console.log(isoDate);


// Less than 6 digits microseconds example
let smallTs = 50
console.log(new Date(smallTs/1e3).toISOString().slice(0, -4) + String(smallTs).slice(-6).padStart(6, '0') + 'Z');

RobG example cannot convert smaller than 6 Digits microseconds like 500 or 50 to ISO String correctly. Thank you for your answer though.

Abrar Ahmed
  • 124
  • 1
  • 3
  • 14