Date Rendering Problem on Front-end with Different Time Zones

94 views Asked by At

I am facing a problem in rendering dates within my web app of a bank when there are differences in time zones. The backend provides the dates in the correct format, but during the rendering on the front end, discrepancies are found, especially when the time zone is different from that of Rome (UTC+2).

Details:

I use React for my web app. Dates are provided by the backend in the UTC format: "2021-04-01T00:00:00.000+02:00". I implemented the dateformat function using the Moment.js library to format dates. I have noticed that the problem arises when the time difference is more than two hours compared to Rome.

Code:

export const placeholderForNullOrUndefined = '-';

export const dateFormat = (value?: any) => {
  console.log('Real value:', value)
  if (!value) {
    return placeholderForNullOrUndefined;
  }

  const DATE_FORMAT = "DD/MM/YYYY";

  if (!(value instanceof Date)) {
    return moment(value).format(DATE_FORMAT);
  }

  console.log('value', value);

  const data = value;
  const stringDate = value;
  const momentValue = moment(stringDate);
  const timezone = data.getTimezoneOffset() / 60;
  console.log('timezone', timezone);

  return momentValue.utc(true).format(DATE_FORMAT);
};

Additional Questions:

How can I ensure that dates are rendered correctly regardless of time zone? Are there any adjustments I can make to the dateformat function to better handle differences in time zones? Thank you so much for your help!

I expect the dates to be equal both front and back end

0

There are 0 answers