skip to Main Content

I have a React Native app, running React Native 0.71.9 and React 18.

I have an API returning data and I parse that data into models (using Mobx). When I try to create a new Date object using the format "mm/dd/yy" (e.g. 09/03/23) it returns "Invalid time".

This happens usually when running the app in Pacific timezone, when current date is the day before to the date I want to parse.

The purpose is to get the date with midnight time.

// Today is 09/02/23, in Pacific timezone
// It's in 09/03/23 in UCT time
const date = new Date("09/03/23") // returns "Invalid time". Instead I'd like to get 09/03/23 00:00:00 

What’s the reason behind this?

2

Answers


  1. Consider appending the desired timezone:

    const date = new Date("09/03/23 00:00:00 GMT-0700");  // For Pacific Daylight Time
    
    Login or Signup to reply.
  2. Hypothesis on the problem

    The JavaScript specification specifies valid string formats accepted by the date constructor. MM/DD/YY is not one of them. Non-standard formats can be parsed in any way, it’s up to the implementers of the JavaScript runtime.

    In React Native, there are two possible JavaScript runtimes (reference):

    Hermes only supports formats defined in the spec (reference). I also tested by evaluating new Date("09/03/23") in the Hermes REPL and it returned [Date Invalid].

    JavaScriptCore seems to support MM/DD/YY. WebKit browsers use JavaScriptCore so I tested by evaluating new Date("09/03/23") in the console in Safari (a WebKit browser). It returned Sun Sep 03 2023 00:00:00 GMT+0100 (British Summer Time).

    As a result, I hypothesise different versions of your app may be running different JavaScript runtimes. The version running Hermes will error while the version running JavaScriptCore won’t.

    Testing the hypothesis

    Some initial questions that might validate the hypothesis without too much effort:

    • Did you recently enable Hermes in your app?
    • Did you recently upgrade React Native? Hermes was available in 0.64 and enabled by default in 0.70 (reference).
    • Does the problem only affect a certain version range of your app?

    If the answers to the above questions aren’t helpful in validating the hypothesis then you will probably need to check if Hermes is enabled now and wasn’t before. Check the configuration for enabling Hermes and step through your codebase history to verify if Hermes was disabled/enabled and when.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search