Skip to content
Advertisement

Moment.js formatting date field to a day earlier than it should

This is a very small little bug I’m trying to fix in my code. I have a React component with this initial state

const initialFormData = Object.freeze({
    date: Moment(new Date()).format('YYYY-MM-DD'),
    price_per_gallon: '',
    trip_distance: '',
    gallons: '',
    car: ''
});

const [formData, updateFormData] = useState(initialFormData);

Which is used in a form like so:

<MuiPickersUtilsProvider utils={DateFnsUtils}>
    <Grid container justifyContent="space-around">
        <KeyboardDatePicker
            fullWidth
            disableToolbar
            inputVariant="outlined"
            format="yyyy-MM-dd"
            margin="normal"
            id="date-picker-inline"
            label="Date of Fillup"
            name="date"
            value={formData.date}
            onChange={handleDateChange}
            KeyboardButtonProps={{
                'aria-label': 'change date',
        }}
        />
    </Grid>
</MuiPickersUtilsProvider>

I’ve done console.logs to see that the Moment(new Date()).format(‘YYYY-MM-DD’) shows today’s date, as I want, but for some reason when the component renders it has the default date in the field as yesterdayenter image description here, but if I were to get rid of initializing the date with the Moment instance and just have it be ‘new Date()’, it renders with today’s date correctly.

Any idea why this could be? Kind of wracking my brain here, I just want the default date on my form to be whatever the current day is, and need to format it to YYYY-MM-DD because that’s how my API sends and receives the data

Edit: Here are three console.logs I’ve tried:

console.log(new Date());
console.log(Moment(new Date()).format('YYYY-MM-DD'));
console.log(Moment().format('YYYY-MM-DD'));

and their results:

Wed Feb 09 2022 22:01:41 GMT-0500 (Eastern Standard Time)
2022-02-09
2022-02-09

But for some reason the second two using Moment will cause the component to render with yesterday’s date

Advertisement

Answer

First, you can emove the plain JS new Date() as agument to moment.

date: moment().format('YYYY-MM-DD')

No argument is necesssary to moment to have a moment object for local time. It’s the default 😉

Then, as mentionned in comments by Vengleab SO, you are passing that date to KeyboardDatePicker which (most probably) assumes that is a UTC date and “removes” your time offset from it. That would explain why the date is yesterday when testing it between 19H00 and midnight (your local GMT-5 time).

So… Just passing a time along the date should fix the issue.

date: moment().format('YYYY-MM-DD 12:00:00')
Advertisement