Home > Blockchain >  Format string date and time using MomentJs in React project
Format string date and time using MomentJs in React project

Time:08-26

I have api that provides the date and time and I need to format it. Its a react project and I am using momentJs. I am open to other methods.

Currently I get error that invalid date

// this is the exact string that is coming from api
const fromApi = "2022-08-23 00:10:29  0000"

return(
  <div>
    {moment(fromApi).format('MMMM Do YYYY')}
  </div>

CodePudding user response:

While parsing the date you need also pass the format your date string is in. I can see that this is a react code I would suggest you declare a variable to store the date and use it in your JSX. For Example:

const fromApi = "2022-08-23 00:10:29  0000"
const someday = moment("2022-08-23 00:10:29  0000","YYYY-MM-DD");

return(
  <div>
    {someday}
  </div>   

This would do but if you want to optimize the code then you must use useMemo to cache someday value so that it is not re calculated every time you call function. Just Like:

const someday = useMemo(()=>moment("2022-08-23 00:10:29  0000","YYYY-MM-DD"),[]);

CodePudding user response:

I work ok with your code, i think you should check fromApi from api before render to moment(), because fromApi able undefined.

const fromApi = "2022-08-23 00:10:29  0000"

return(
  <div>
    {fromApi && moment(fromApi).format('MMMM Do YYYY')}
  </div>
  • Related