Home > database >  Moment.js - Inconsistent date on different devices
Moment.js - Inconsistent date on different devices

Time:09-24

I am facing some issues with displaying dates. when users select a date i am formatting it like this

new Date(date).toISOString().split('T')[0];

because this is the format our django backend expects and then the backend returns a date like this:

2021-09-02

then I am formatting the date returned from the backend with moment.js:

moment.utc(new Date(date)).format('MMM DD')

But the problem is that when I select "September 25" I get "Sep 25".

But some of my team members who are in India select "September 25" they get "Sep 24".

If I run new Date('2021-09-02') in my dev tools.

I get Wed Sep 01 2021 17:00:00 GMT-0700 (Pacific Daylight Time)

and they get Date Thu Sep 02 2021 05:30:00 GMT 0530 (India Standard Time)

How can I handle this edge case? I'm not sure if I need to update the format stored on the backend. need your suggestions

CodePudding user response:

This is a time zone issue, and the problem seems to be that you would like to select a date (25th September), but you are actually selecting a time and then converting it to a string to represent a date.

When your user selects a date, could you just have them select the day and the month, instead of a whole time?

Edit

Hmm, sorry, the issue isn't in the selecting of the date, but in turning the date returned from your server back into a time. But you don't want a time, you just want a date.

Your server is returning a string like "2021-09-25" to signify "Sep 25". You could parse this string and get the important parts:

function displayDayMonth(date) {
  const [_year, month, day] = date.split("-").map(s => parseInt(s, 10));
  const months = ["Jan", "Feb", //... etc ];
  return `${months[month - 1]} ${day}`;
}

const date = "2021-09-25";
displayDayMonth(date);
// => "Sep 25"

On the other hand, what happens if the time actually matters? If an event in Pacific Time is on the 25th September, then a good portion of that event occurs on the 24th September in India. Perhaps you are not capturing enough detail about the event?

  • Related