arthuro ali
arthuro ali

Reputation: 137

I'm wasting a day on dates

I am having problems since I am saving some dates and they are saved well in the database, when I show them I have one day left, for example if I enter 09/30/2020 it shows me 09/29/2020, I have tried some solutions like adding T00: 00: 00 but that makes an invalid date, plus the backend is taking care of that. Here's a bit of my code, in case someone can give me a hand.

 showDatesDependingOnWhichExists = (status) =>{
  if(status.estimatedDate != undefined || "" && status.comment == undefined || "" && 
  status.startDate == undefined || "" && status.finishDate == undefined || "" ){
    return (<td>{moment(new Date(status.estimatedDate)).format("DD/MM/YYYY")}</td>)
  }else if(status.startDate != undefined || "" && 
  status.finishDate != undefined || "" && status.comment == undefined || "" ){
    return (<td>{moment(new Date(status.startDate)).format('DD / MM / YYYY') + "  -  " + moment(new Date(status.finishDate)).format('DD / MM / YYYY')}</td>)
  }else if(status.comment != undefined || "" ){
    return (<td>{moment(new Date(status.startDate)).format('DD / MM / YYYY') + "  -  " + moment(new Date(status.finishDate)).format('DD / MM / YYYY')}</td>)
  }
}

Upvotes: 0

Views: 36

Answers (2)

Matt G
Matt G

Reputation: 346

I think @AbdulMoeez is correct in his comment to your question. You are likely storing the date as UTC in the database or inadvertently converting it to UTC in the server layer. Then you display it as the local time zone in the client, which is causing it to (correctly) display as a different date.

Upvotes: 1

hgb123
hgb123

Reputation: 14891

You should cast it to UTC mode using .utc, otherwise it would use your local timezone to parse the date

The doc states that

By default, moment parses and displays in local time.

If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment()

const time = "2020-09-30T00:00:00.000Z"

console.log(moment.utc(time).format("MM/DD/YYYY"))
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Upvotes: 2

Related Questions