DEV Community

Deni Sugiarto
Deni Sugiarto

Posted on • Updated on

Invalid Date in Safari

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

Top comments (4)

Collapse
 
jayantbh profile image
Jayant Bhawal

I'd say instead of calling that function formatDateForSafari, you might want to call it dateStringToISO or something along those lines.

Because this function will absolutely get copy-pasted and end up in someone's production codebase someday. 🤣

Collapse
 
deni_sugiarto_1a01ad7c3fb profile image
Deni Sugiarto

Thanks for your advice. I will change it

Collapse
 
hendrikras profile image
Hendrik Ras

I was facing this very issue with Safari, when by chance I read your post. Thank you.

Collapse
 
kanish profile image
Kanish Ravikumar

Hi, this is great. As a web dev I face so many issues that appear in safari that doesn't appear in chrome or opera or any other browser. This is going to be very helpful, thank you!