Issue
This Content is from Stack Overflow. Question asked by JamieRhys
I seem to be having a bit of a weird bug wherein as the title states, MomentJS is providing a time that is an hour behind. This is my code so far:
import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment";
import moment from "moment";
...
const [job, setJob] = useState({
name: "",
outgoingDateTime: moment.now(),
jobStartDateTime: moment.now(),
returningDateTime: moment.now(),
jobFinishDateTime: moment.now(),
isJobStartLinked: jobStartLinked,
isJobFinishLinked: jobFinishLinked,
contact: null,
});
const handleOutgoingDateTimeChange = (newValue) => { setJob({...job, outgoingDateTime: newValue}); }
With the above code, when I trigger the DateTimePicker to be displayed, it displays the correct time. For example, if I trigger it on 19/09/2022 at 23:45, it will display 19/09/2022 23:45
.
This is what I’m using to display this:
<LocalizationProvider dateAdapter={AdapterMoment}>
<DateTimePicker
label="Outgoing Date and Time"
value={job.outgoingDateTime}
onChange={handleOutgoingDateTimeChange}
inputFormat="DD/MM/YYYY HH:mm"
ampm={false}
renderInput={(params) => <TextField {...params} />} />
</LocalizationProvider>
Might I also add that when I change the value of the DateTimePicker, it correctly states the input. For example, let’s say I input 25/09/2022 07:30. It would display 25/09/2022 07:30
.
Now, when I then tap save, the returned value is an hour behind. So, for example, let’s take what I entered just now 25/09/2022 07:30
. It would come back as 25/09/2022 06:30
.
I’m checking my back end to see if that was the issue, however, upon doing so, I could see that the front end is passing along the hour behind data.
What could be happening and how could I fix this?
Solution
So, after looking into this a little further, I found that my back end was using LocalDateTime which, living in the UK is bad… Bad because LocalDateTime is not Daylight Saving aware. After changing the variables to ZonedDateTime (which is DST aware) and zoning it in to Europe/London, it now saves to the database properly.
This Question was asked in StackOverflow by JamieRhys and Answered by JamieRhys It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.