简体   繁体   中英

If the react native debugger is off, moment returns an invalid date

In my RN application, I have the following code.

const birthDate = moment(new Date(val));

If the RN debugger is off it returns an invalid date error. But if the RN debugger is on, it returns the correct date.

What is the issue here?

This issue was already discussed here . The problem originates from different JavaScript Runtime Environments and the fact that the new date constructor is quite picky. You can overcome that issue by using moment directly to create new dates or write a small function as https://github.com/SahRckr in the github issue proposed:

// SahRckr's proposal 
const jsCoreDateCreator = (dateString) => { 
  // dateString *HAS* to be in this format "YYYY-MM-DD HH:MM:SS"  
  let dateParam = dateString.split(/[\s-:]/)  
  dateParam[1] = (parseInt(dateParam[1], 10) - 1).toString()  
  return new Date(...dateParam)  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM