Convertion of formatted date string to DaysJS date object for the current locale

103 Views Asked by At

I need to create a function to obtain a Dayjs object from an input formatted date string. The input text is the result of the format method, but it can be formatted in different ways, primarily to "L LT" but not exclusively.

In my app, the user can change the application language, and it consequently changes the Dayjs locale as well, functioning effectively. For the Polish locale, the format is "04.02.2024 23:00"; for British English, it is "02/04/2024 11:00 PM"; and for German, it is "04.02.2024 23:00". I utilize the Dayjs plugins localizedFormat and utc.

Users can input any formatted date string into the search bar in a table. That's why I have to handle all possible formats. However, I encountered an issue.

When I enter a formatted date string into the Dayjs function, it swaps the positions of the month and day. For example, for "04.02.2024" in the Polish locale, the day should be at 4, and the month at 2. I verified the Polish locale configuration, and it is as it should be 'L: DD.MM.YYYY'.

  const dateFromAPI: Dayjs = dayjs('2024-02-04T23:00:00+01:00')
  const formattedDate: string = dateFromAPI.format('L LT') //Returns "04.02.2024 23:00"
  const date: Dayjs = dayjs(formattedDate) //Contains $L: "pl", $D: 2, $M: 4
  const formattedAgain: string = date.format('L LT') //Returns "02.04.2024 23:00"

In the above code, you can observe that creating a new Dayjs object from formattedDate results in an incorrect value. I attempted to resolve this issue by adding a format template, such as dayjs(formattedDate, {format: 'DD.MM.YYYY HH:mm'}), but this approach was unsuccessful. Moreover, it should not be done in this way because I need to handle all of date formats.

What can I do to consistently obtain the correct Dayjs object from a formatted date string returned by Dayjs?

0

There are 0 best solutions below