skip to Main Content

I am working with reactjs and i am using "nextjs" framework, I am fetching "blogs data" using loop, but problem is "i want to change date format of blogs"
Here is my current code

{user && user.length > 0 && user.map((userObj, index) => (
                      <NewsCard
                    key={index}
                    img={userObj.image}
                    title={userObj.title}
                    date={userObj.CreatedAt}   // getting date for example "2023-03-26 01:40:26"
        />
                ))}

My expected date format is for example
April 29,2023
How can i do this ?

2

Answers


  1. You can use Date.toLocaleString() and specifiy the desired format with it:

    const date=new Date().toLocaleString("en-US",{month:"long", day:"numeric", year:"numeric"});
    
    console.log(date)

    So, I guess, in your React pag you should put something like

    date={userObj.Created.toLocaleString("en-US",{month:"long", day:"numeric", year:"numeric"})}
    
    Login or Signup to reply.
  2. Use the toLocaleDateString() method to convert the date

    {user && user.length > 0 && user.map((userObj, index) => (
        <NewsCard
            key={index}
            img={userObj.image}
            title={userObj.title}
            date={new Date(userObj.CreatedAt).toLocaleDateString('en-US', {
                month: 'long',
                day: 'numeric',
                year: 'numeric',
            })}
        />
    ))}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search