Invalid Date in Safari

Deni Sugiarto - Jul 8 - - Dev Community

Hello everyone,

Today, I encountered a weird bug that only appears in the Safari browser. It works fine in other browsers. After debugging the code in Safari, I found that filtering data by date was resulting in an empty array. I have been using dayjs as my date library for formatting and filtering.

Here is the source date I use: "2024-7-1,6:0:0".

After some research, I discovered that Safari requires dates to be in ISO 8601 format. To handle this, I created a function formatDateForSafari that converts a date string into the ISO 8601 format. Here is the code:

function dateStringToISO(dateString) {
  const date = new Date(dateString);

  // Check if the date is valid
  if (isNaN(date.getTime())) {
    throw new Error("Invalid date");
  }

  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');

  return `${year}-${month}-${day}`;
}

// Example usage:
const date = "2024-7-1,6:0:0";
console.log(dateStringToISO(date)); // Output: 2024-07-01
Enter fullscreen mode Exit fullscreen mode

By using this function, you can ensure that your date strings are properly formatted for Safari, avoiding issues with invalid dates.

This version maintains your original points while improving readability and coherence.

Update function name regarding @jayantbh suggestions. Thanks for your suggestion

. . . . . . . .
Terabox Video Player