fecha icon indicating copy to clipboard operation
fecha copied to clipboard

Getting "Invalid Date pass to format" on iOS Chrome but not on Web

Open diegogallovich opened this issue 1 year ago • 2 comments

Hi @taylorhakes, I am hoping to reach you by opening this issue and also help anybody that might have encountered this problem before.

Issue while: Generating a YYYY-MM-DD date using fecha.format(dateObj, 'YYYY-MM-DD')

Notes on the issue: When formatting the date, for some reason on a desktop, the function works like a charm in any web browser I've tested (firefox, safari, chrome). However, on iOS, in Chrome and Safari, I keep receiving an "Invalid Date pass to format" error (See screenshot).

Code I am using: data: { checkIn: fecha.format( new Date(datepicker.getValue().split(' - ')[0]), 'YYYY-MM-DD' ), checkOut: fecha.format( new Date(datepicker.getValue().split(' - ')[1]), 'YYYY-MM-DD' ) },

  • As you can see in the screenshot, two date strings are logged. These are the ones being passed to the function derived from the split.

image

I am looking forward to your response.

diegogallovich avatar May 23 '23 18:05 diegogallovich

I don't have time to debug this issue unfortunately. If you are able to find the issue and provide a fix, I will happily merge it

taylorhakes avatar May 24 '23 17:05 taylorhakes

Hi @taylorhakes, so the issue is a matter of how different devices/browsers are able to work with date strings.

The issue seems to be when performing a parsing function on the Date

Specifically, some platforms (like certain mobile browsers) may not be able to parse date strings in the "MM-DD-YYYY" format. They expect the format "YYYY-MM-DD" instead. This discrepancy leads to the RangeError: Invalid date error.

A safer and more reliable approach is to manually parse date strings. Here is an example:

let parseDate = dateStr => { let [month, day, year] = dateStr.split('-').map(Number); return new Date(year, month - 1, day); };

this is what I ended up implementing on my end. Hope it helps. If I find the time to look into the library and find where you are parsing the other way, such as:

let formatDate = date => date.toISOString().slice(0,10);

... I will open a pull request for you to merge.

diegogallovich avatar May 24 '23 18:05 diegogallovich