Backend give me data of gantt diagramm start and end points in format:
"horizont_start": "2024-05-01T00:00:00Z",
"horizont_end": "2025-01-26T00:00:00Z",
Next i give through props to another component Date format of this points like this:
<NewGanttChart
start={
new Date(
gantt?.horizont_start ||
new Date(
new Date().getFullYear(),
0,
1
)
)
}
end={
new Date(
gantt?.horizont_end ||
new Date()
)
}
data={gantt?.machine_types || []}
isTooltip={true}
tooltip={tooltip}
/>
in component i use function to calculate timeAxis intervals:
//also save in store start and end time
useEffect(() => {
dispatch(setStartTime(start?.getTime()))
dispatch(setEndTime(end?.getTime()))
}, [start, end])
const timeAxis = useMemo(() => {
const axisLength = Math.ceil((end - start) / (measure * 60 * 60 * 1000))
const axisDates = new Array(axisLength).fill(0).map((_, i) => {
const date = new Date(start.getTime())
const newDate = new Date(+date + 1000 * 60 * 60 * measure * i)
return newDate.getTime()
})
console.log(axisDates)
return axisDates
}, [end, measure, start])
My main problem is local time, so i want to show start point time 00:00:00, but i got +5h 05:00:00, how to solve this problem?
PS: one more time with logs
console.log(gantt?.horizont_start) // output 2024-05-01T00:00:00Z
console.log(new Date(gantt?.horizont_start)) // output Wed May 01 2024 05:00:00 GMT+0500 (Uzbekistan Standard Time)
3
Answers
So, i've decided to get timeZoneOffSet and use it in my function like this and it's working for me:
When you create a new date instance with the returned string it will be in client local time:
Looks like it is the only way using
.toISOString()
to display it as it is.The time
00:00:00
UTC is the same moment in time as05:00:00
in a +5h time zone.To solve you issue you’ll probably want to be working with the UTC representation. To do this replace the Date methods you’re using to their UTC variants:
getUTCDate()
/setUTCDate()
getUTCDay()
getUTCFullYear()
/setUTCFullYear
getUTCHours()
/setUTCHours()
getUTCMilliseconds()
/setUTCMilliseconds()
getUTCMinutes()
/setUTCMinutes()
getUTCMonth()
/setUTCMonth()
getUTCSeconds()
/setUTCSeconds()
To log/display the time you can use
toUTCString()
ortoISOString()
, depending on the preferred format.Working with the above methods lets you work with the same time zone that the server provides. Meaning that time doesn’t jump, assuming the server always provides UTC time.
Alternatively you could ignore the time zone, and read the dates in local time. This can be done by chopping of the
Z
which denotes UTC.WARNING: Do note that
2024-05-01T00:00:00Z
and2024-05-01T00:00:00+05:00
are two different moments in time:So if the exact moment in time is important you do NOT want to use this method.