Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

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')
about 4 years ago · Juan Pablo Isaza Relatório

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda