Skip to content

When formatting date object – does it matter that the T and the 000Z will be removed when storing to db?

Sorry if its a very basic question but I dont understand the following:

When I format the Date object (no matter what library I used), I get a string.

from this: 2022-11-28T16:55:44.000Z (new Date object)
I get this: 2022-11-28 16:55:44 (or other formats obviously depending how I format it)

Even if I turn it back into an object it, the T and 000Z will never be there anymore. Do I just ignore that (seems like it as any library or date methods are ignoring the T and the string ending when formatting) or do I add it ‘back’ Isnt it a problem if dates stored in my db are different (for later queries etc.)?



I see it even stronger: You should never store dates as strings, it’s a design flaw. Store always proper Date objects. Here on SO you can find hundreds of questions, where people have problems, because they stored date values as (localized) strings. It is not limited to MongoDB, it applies to any database.

Date objects in MongoDB are UTC times – always and only! Usually the client application is responsible to display the date/time in local time zone and local format.

What do you mean by “turn it back”, i.e. how do you do it?

You should not rely on new Date(<string>) without time zone. Some browsers/environments may apply UTC time, others may use current local time zone, see Differences in assumed time zone

Have a look at 3rd party date libraries, e.g. moment.js, Luxon, or Day.js. Usually they provide better control how to parse strings and time zones.