0

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?

Jay
  • 339
  • 1
  • 7
  • 23

3 Answers3

2

round the milliseconds part and replace trailing 0Z

new Date(Math.round(new Date().getTime() / 10) * 10).toISOString().replace('0Z', 'Z')

if it is simple truncating, use Math.floor or regexp replacement

new Date(Math.floor(new Date().getTime() / 10) * 10).toISOString().replace('0Z', 'Z')
new Date().toISOString().replace(/\dZ$/, 'Z')
ProDec
  • 5,390
  • 1
  • 3
  • 12
2

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)
Phil
  • 157,677
  • 23
  • 242
  • 245
0

If you are fine with truncating, rather than rounding, this is fun, though rather cryptic:

> d = new Date().toISOString()
'2021-11-02T06:00:01.601Z'
> d.replace(/(\d\d\.\d\d)\d/, "$1",)
'2021-11-02T06:00:01.60Z'

It relies on toISOString always producing 3 digits after the radix point. Here you can use replace to just keep the first two digits.

Here's another run:

> d = new Date().toISOString()
'2021-11-02T06:02:25.420Z'
> d.replace(/(\d\d\.\d\d)\d/, "$1",)
'2021-11-02T06:02:25.42Z'

As I mentioned, it does truncate rather than round, so you may notice cases like these:

> d = new Date().toISOString()
'2021-11-02T06:03:53.157Z'
> d.replace(/(\d\d\.\d\d)\d/, "$1",)
'2021-11-02T06:03:53.15Z'

Now if you really want the rounding, try this:

> d.replace(/(\d\d\.\d\d\d)/, s=>Number(s).toFixed(2))
'2021-11-02T06:03:53.16Z'

That one has the advantage of doing the work on actual numbers. But it will fail for seconds between 0 and 9, so to borrow from Phil's correct answer, use padStart to make sure to keep the leading zero in for seconds:

> d = '2021-11-02T06:22:03.266Z'
> d.replace(/(\d\d\.\d\d\d)/, s=>Number(s).toFixed(2).padStart(5, '0'))
'2021-11-02T06:22:03.27Z'

Phil's regex is more general, too, so accept that answer.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232