#Date Hydration Mismatch

3 messages · Page 1 of 1 (latest)

floral field
#

Hello,

I write on a new system, I have a Timestamp and must convert them to show to the user. The problem is that I get a Hydration Mismatch because the Server and the Client Handel the Date Time Zone different.

Input:
2023-07-23T20:06:00.717913+00:00

Output Server: 23.07.2023 20:06
Output Client: 23.07.2023 22:06

How I can handle that both systems gave me the same string to avoid the Hydration Mismatch. I don't want only render the time on the client, a solution I often found in my research because of SEO, I want that's rendered on the server side correctly.

My Function to Convert the Date:

export function useFormatDate (date: string): string {
  const dateObject = new Date(date)

  const day = dateObject.getDate()
  const month = dateObject.getMonth() + 1 // Adding 1 to the month since it is zero-based
  const year = dateObject.getFullYear()

  const hour = dateObject.getHours()
  const minute = dateObject.getMinutes()

  const formattedDay = day.toString().padStart(2, '0')
  const formattedMonth = month.toString().padStart(2, '0')
  const formattedYear = year.toString()
  const formattedHour = hour.toString().padStart(2, '0')
  const formattedMinute = minute.toString().padStart(2, '0')

  return `${formattedDay}.${formattedMonth}.${formattedYear} ${formattedHour}:${formattedMinute}`
}

Can you give me some idea to do this correctly?

slender dome
#

Hi Felix, I think this is one of the most common ssr mismatch issues across all frameworks.

Option 1: You can solve this by using Intl.DateTimeFormat with the timeZone option set to the same on client & server. This would guarantee that no matter in which timezone your client & server is, it would always generate the same string. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
After the client has finished rendered without mismatches. You could update the rendered date and make sure it now includes the real user's timezone.

Option 2: Another option would be to do a process.client check, meaning that you render something different on purpose. But I am not 100% sure if this does not trigger a mismatch too.

if (process.client) {
  return // date formatted with client's timezone
} else {
  return // date formatted by server timezone
}
heavy sedge