Search code examples
javascripttoisostring

JavaScript - Convert date to ISOString() with milliseconds rounded to two digit


I am trying to set a date that has ISOString format but the milliseconds should be set to two digits.

If the ISOString returns 2021-11-02T05:49:12.704Z I want it to be 2021-11-02T05:49:12.70Z (milliseconds round to two places)

This is what I am trying to do.

let startdate = new Date();
console.log(startdate.getMilliseconds()); //just to check
let d = startdate.toString().replace(microsecond=Math.round(startdate.microsecond, 2))  
console.log(d) //format is different
startdate =  startdate.toISOString() //this is different than d
console.log(startdate)

Output for this is

961
Tue Nov 02 2021 05:50:46 GMT+0000 (Coordinated Universal Time)
2021-11-02T05:50:46.961Z

Can anyone help?


Solution

  • Parse out the seconds and millis and replace it with a fixed precision number

    const now = new Date()
    const formatted = now
      .toISOString()
      .replace(/\d{2}\.\d{3,}(?=Z$)/, num =>
        Number(num).toFixed(2).padStart(5, "0"))
      
    console.log(formatted)