🏠 back to Observable

Date formatter returns NaN on mobile

This notebook displays formatted date objects below each chart using the following code:

// Store a formatted version to display below each chart
      const date_pieces = date.split("/");
      const date_str = date_pieces[0] + " " + date_pieces[1];
      obj.x_min_label = parseDate(new Date(date_str));

This works just fine on desktop, but returns NaN on mobile (strange…). Any thoughts?

mobile_error

You’re basically doing:

new Date('3 10')

that returns “Invalid date”. It would be better to pass the date to new Date as an ISO8601 string to be sure to parse it as expected.

Note: I get NaN too on desktop, using Firefox. Maybe the configured locale can be an issue in your case.

Or much simpler, as you already have year, month and day, to pass these values as the three first arguments. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date. Be careful that the month indexes must start at 0.

3 Likes

Great, thanks! Strange how different browsers // operating systems handle dates differently. Appreciate it!

1 Like

Usually that’s a left-over from before proper standardization. When in doubt it’s a good idea to check MDN (like the link severo gave) to see what works now, and to double check if you’re dealing with a stable or unstable API.

2 Likes