Idea const d = new Date() returns the date object getters like d.getHours() return local time with GMT shift based on client's device getters like d.getUTCHours() return UTC time API call returns the date object parsed on server side with 0 timezone shift Same object on the client side returns local time with local timezone UTC time is the same on both sides Do not rely on server local time if you present time to a client, take the date object and parse it on client's device Date on server vs client Code Server
// pages/api/time_on_server.js
import { ddmmyyyyHHMMSS } from '/functions/ddmmyyyyHHMMSS'
export default async function handler(req, res) {
const d = new Date()
res.json({
'd = new Date()': new Date(),
'd.getFullYear()': d.getFullYear(),
'd.getMonth()': d.getMonth(),
'd.getDate()': d.getDate(),
'd.getHours()': d.getHours(),
'd.getMinutes()': d.getMinutes(),
'd.getSeconds()': d.getSeconds(),
'd.getMilliseconds()': d.getMilliseconds(),
'd.getDay()': d.getDay(),
'd.getTimezoneOffset()': d.getTimezoneOffset(),
'd.getTime()': d.getTime(),
'd.getUTCFullYear()': d.getUTCFullYear(),
'd.getUTCMonth()': d.getUTCMonth(),
'd.getUTCDate()': d.getUTCDate(),
'd.getUTCHours()': d.getUTCHours(),
'd.getUTCMinutes()': d.getUTCMinutes(),
'd.getUTCSeconds()': d.getUTCSeconds(),
'd.getUTCMilliseconds()': d.getUTCMilliseconds(),
'd.getUTCDay()': d.getUTCDay(),
'd.toDateString()': d.toDateString(),
'd.toISOString()': d.toISOString(),
'd.toJSON()': d.toJSON(),
'd.toGMTString()': d.toGMTString(),
'd.toLocaleDateString()': d.toLocaleDateString(),
'd.toString()': d.toString(),
'd.toTimeString()': d.toTimeString(),
'd.toUTCString()': d.toUTCString(),
'd.valueOf()': d.valueOf(),
formatted: ddmmyyyyHHMMSS(d.toString()),
formattedUTC: ddmmyyyyHHMMSS(d.toString(), true)
})
}
Client
import { ddmmyyyyHHMMSS } from '/functions/ddmmyyyyHHMMSS'
function DateFromServer() {
const [response, setResponse] = useState('Loading...')
useEffect(getDateObj, [])
async function getDateObj () {
const url = '/api/time_on_server'
const response = await fetch(url)
const result = await response.json()
console.log(result)
setResponse(result)
}
return (
<>
<Hs>UTC</Hs>
<div>Date on <b>server</b> (UTC): {response.formattedUTC}</div>
<div>Date on <b>client</b> (UTC): {ddmmyyyyHHMMSS(new Date(), true)}</div>
<Hs>Local</Hs>
<div>Date on <b>server</b> (local): {response.formatted}</div>
<div>Date on <b>client</b> (local): {ddmmyyyyHHMMSS(new Date())}</div>
</>
)
}