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 formatDateForSafari(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(formatDateForSafari(date)); // Output: 2024-07-01
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.