Home > Mobile >  Converting date from mongoDb/mongoose in react
Converting date from mongoDb/mongoose in react

Time:10-01

I have an application using mongodb/mongoose with a field called eventStartDate set to a type of Date

eventStartDate: {
  type: Date,
},

I'm using a date picker input field with type='date'. When I select a date, and submit it goes into the database as 2022-09-03T00:00:00.000 00:00 butt when I try to query it (I'm using graphql) I just get a long string of numbers like this: 1666396800000.

How can I convert that date to display it properly as 09/03/2022.

CodePudding user response:

Following worked for me.

 var inputDate = "1666396800000"; // As mentioned long string of numbers
 function convert(input) {
    var date = new Date(input),
    mnth = ("0"   (date.getMonth()   1)).slice(-2),
    day = ("0"   date.getDate()).slice(-2);
    return [mnth, day, date.getFullYear()].join("/");
 }

 console.log(convert(parseInt(inputDate))); // 10/21/2022

Convert date from 'Thu Jun 09 2011 00:00:00 GMT 0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

CodePudding user response:

As usual, I posted the question after days of trying to figure it out, then figured it out.

When I just tried to convert the data as it was I either got Invalid date or NaN or something like that. Then I rezlied the ling interger was a string so I tried converting it to an integer and then used momentjs to format the date.

let tempDate = parseInt(eventData.eventStartDate);
    setEventStartDate(moment(tempDate).add(1, 'days').format('YYYY-MM-DD'));

I set the date ad YYYY-MM-DD so it would populate the date input field when going back to edit the event.

  • Related