Home > Enterprise >  Convert date string to MM DD in react - not vanilla JS
Convert date string to MM DD in react - not vanilla JS

Time:12-13

I understand how to do this outside of react. I have a date string that is returned from API in an object. I need to reformat it so instead of "2022-12-13T06:00Z" it would read "December 13". The object holds utcStart as "2022-12-13T06:00Z". Currently the below displays as "2022-12-13T06:00Z"

const eventDates = useRecoilValue(eventDatesState);
return (
    <Grid item xs={12}>
        eventDates.map (data =>(
            <ListItem>
                <span className="date">{eventDates.utcStart}</span>
            </ListItem>
        ))
    </Grid>
)

Since it is in a map function, I don't know how to do this for each one.This doesn't work

<span className="date">{new Date(calendarContent.utcStart)}</span>

CodePudding user response:

You can do something like this:

var date = new Date('2022-12-13T06:00Z');

// Use the options object to specify the desired format
var options = { month: 'long', day: 'numeric' };
var formattedDate = date.toLocaleDateString('en-US', options);

console.log(formattedDate);
// OUTPUT
// December 13

CodePudding user response:

Example using the answer above:

export default function GridWithFormattedDates() {
    const eventDates = useRecoilValue(eventDatesState);
    return (
        <Grid item xs={12}>
            {eventDates.map(eventDate => {
                const date = new Date(eventDate);

                const options = { month: 'long', day: 'numeric' };
                const formattedDate = date.toLocaleDateString('en-US', options);
                return (
                    <ListItem>
                        <span className="date">{formattedDate}</span>
                    </ListItem>
                );
            })}
        </Grid>
    );
}
  • Related