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…


This content originally appeared on DEV Community and was authored by deni sugiarto

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.


This content originally appeared on DEV Community and was authored by deni sugiarto


Print Share Comment Cite Upload Translate Updates
APA

deni sugiarto | Sciencx (2024-07-08T01:43:13+00:00) Invalid Date in Safari. Retrieved from https://www.scien.cx/2024/07/08/invalid-date-in-safari/

MLA
" » Invalid Date in Safari." deni sugiarto | Sciencx - Monday July 8, 2024, https://www.scien.cx/2024/07/08/invalid-date-in-safari/
HARVARD
deni sugiarto | Sciencx Monday July 8, 2024 » Invalid Date in Safari., viewed ,<https://www.scien.cx/2024/07/08/invalid-date-in-safari/>
VANCOUVER
deni sugiarto | Sciencx - » Invalid Date in Safari. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/08/invalid-date-in-safari/
CHICAGO
" » Invalid Date in Safari." deni sugiarto | Sciencx - Accessed . https://www.scien.cx/2024/07/08/invalid-date-in-safari/
IEEE
" » Invalid Date in Safari." deni sugiarto | Sciencx [Online]. Available: https://www.scien.cx/2024/07/08/invalid-date-in-safari/. [Accessed: ]
rf:citation
» Invalid Date in Safari | deni sugiarto | Sciencx | https://www.scien.cx/2024/07/08/invalid-date-in-safari/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.