-1

i am new in NodeJS and mongoDB, i created a variable of Date object when i prints its value it print this

2021-08-06T00:00:00.000+00:00

and stored in database in this format. But i want to store it like this 2021-08-06. i try this way

var date = new Date().toISOString();
      date1 = date.substring(0, 10);
      console.log("date")
      console.log(date1);

its output is this

date
2021-08-06

and when i pass this variable into date field, like this

document.Date = date1;

it insert into database in this formart2021-08-06T00:00:00.000+00:00

please help how to fix this issue.

TimeToCode
  • 1,458
  • 3
  • 18
  • 60
  • Does this answer your question? [What is the best way to store dates in MongoDB?](https://stackoverflow.com/questions/6764821/what-is-the-best-way-to-store-dates-in-mongodb) – esqew Aug 06 '21 at 12:49
  • MongoDB does not have a date data type that does not include time data as well. – esqew Aug 06 '21 at 12:50
  • my question is how to store date without time, in date format, how i can do this? – TimeToCode Aug 06 '21 at 12:54

1 Answers1

2

it insert into database in this format 2021-08-06T00:00:00.000+00:00

Actually a document like {_id:ObjectId(), dt: Date("2021-08-06") is inserted into the database in this format (see bsonspec.org):

00000000: 2200 0000 075f 6964 0061 0dd3 1dfd af14  "...._id.a......
00000010: db18 d4f9 6109 6474 0000 6cc2 187b 0100  ....a.dt..l..{..
00000020: 0000

The date value there is the 64-bit integer:

hex: 0x000017b18c26c00
decimal: 1628208000000

That is also the format that is returned by the MongoDB server to whatever client program you are using.

The Node.js driver recognizes that is a date type, and so helpfully deserializes that value using the Date constructor, such as:

new Date(1628208000000)

Try that from a REPL, and you will see that it is actually Node that is providing the format that you see:

From the mongo shell, that looks like:

> new Date(1628208000000)
ISODate("2021-08-06T00:00:00Z")

JSON doesn't have a date type, so converting will result in that value becoming string:

> tostrictjson({dt:new Date(1628208000000)})
{ "dt" : { "$date" : "2021-08-06T00:00:00.000-00:00" } }

Again, that is the client, not the database, producing the format that you see.

If you need to display the date in a particular format, use a date formatting library like Datejs, Moment.js, Luxon, etc.

Joe
  • 25,000
  • 3
  • 22
  • 44
  • @Jeo so you mean, if i want to insert the date in this format ```2021-08-07```, i need to use the moment.js etc library? – TimeToCode Aug 07 '21 at 06:18
  • 1
    I mean MongoDB uses exactly 1 format to store dates: UTC number of milliseconds since epoch as a 64-bit integer, so you can't store "2021-08-07" as a date. You can either give up processing that as a date and store it as a string, or you can change the display format on the client side after retrieving the value. – Joe Aug 07 '21 at 20:22