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

250
Visualizações
Difference between converting date into string with toISOString() and JSON.stringify()

I researched about converting date into string in ISO format, and I found two methods to do that giving me the same result '2022-07-29T06:46:54.085Z':

  1. (new Date()).toISOString()
  2. JSON.parse(JSON.stringify(new Date()))

Question:

  • Does JS make two approaches/algorithms of converting date or just one function code just call on different object JSON or Date, If So Which one is the best to use?
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

First of all: less code, easier to maintain

So, new Date().toISOString() is simplest way to return string in ISO format.

Regarding question:

No. The output is the same, because of JSON.stringify logic underneath that returns:

JSON.stringify(new Date())
'"2022-07-29T18:58:14.411Z"'

Because:

The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). Thus, they are treated as strings.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

(new Date).toJSON()
'2022-07-29T18:58:14.411Z'
about 4 years ago · Santiago Trujillo Relatório

0

JSON.parse(JSON.stringify(new Date())) is just the same as new Date().toJSON(). And in the docs for that method we can see

Calling toJSON() returns a string (using toISOString()) representing the Date object's value.

So they're having exactly the same result, calling toISOString() directly is just much more straightforward.

about 4 years ago · Santiago Trujillo Relatório

0

If an object passed to JSON.stringify has a toJSON method, then it's used to set the value within the JSON text (see SerializeJSONProperty step 2.b).

Date instances have a toJSON method that is defined as returning the same value as Date.prototype.toISOString.

I.e.

date.toJSON() === date.toISOString()

by design.

about 4 years ago · Santiago Trujillo 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