-1

I receive a date from a database and log them in my server code (Node.js). It's formatted like this:

Wed Jul 05 2023 00:00:00 GMT-0500 (Central Daylight Time)

Then I do absolutely nothing to it, send to my client, and log what it received:

"2023-07-05T05:00:00.000Z"

How is this possible? What's happening?

Adam Prime
  • 35
  • 1
  • 8
  • 1
    If you want to send a formatted date string, you should format it yourself *before* sending it to the client, because, as @Barna said in his answer, for JSON it is by default stringified (to an ISO string). Maybe [this module](https://github.com/KooiInc/es-date-fiddler) helps. – KooiInc Jul 06 '23 at 15:18
  • `Wed Jul 05 2023 00:00:00 GMT-0500 (Central Daylight Time)` is the default representation of a Date using the `toString()` function. `2023-07-05T05:00:00.000Z` is an ISO-8601 formatted/serialised version for passing between applications. – phuzi Jul 06 '23 at 15:19
  • What you receive from your database is a `Date` object, not a string. `console.log` uses one string formatting (that depends on your system timezone, btw), sending it to the client uses a different serialisation. Nothing wrong with that. – Bergi Jul 06 '23 at 15:32

1 Answers1

2

The JavaScript specification says that that's how Date should be represented in JSON (it's not specified at all by the JSON spec). See What is the "right" JSON date format?

If you want the format you show, convert the Date to a string first:

const d = new Date();
console.log(JSON.stringify(d));
console.log(JSON.stringify(String(d)));
Barmar
  • 741,623
  • 53
  • 500
  • 612