简体   繁体   中英

React - convert date with date-fns

I have a date in this format: 12-21-2021 This date comes from a Redux selector.

So console.log('ccc', lastUpdateDate); at the beginning shows only:

ccc

and after few times shows

ccc 12-21-202

If I use new Date(lastUpdateDate).toDateString() it turns out it works only in Chrome, whereas FireFox and Safari say this is an invalid date.

So I want to convert it in the right way using a function.

So I created this function:

const parseDateWithDashes = (dateToParse) => {
    console.log('dateToParse', dateToParse);

    useEffect((): any => { 
    let finalDate;
    dateToParse instanceof Date && dateToParse.getTime()
        ? (finalDate = format(dateToParse, "yyyy-MM-dd'T'HH:mm:ss.SSSxxx"))
        : null;

    console.log('finalDate', finalDate);

    return finalDate;
    }, [dateToParse]); //since at the beginning it is empty, it should re-run as a date is available
};

parseDateWithDashes(lastUpdateDate)

However doing this it logs out:

dateToParse (several time empty)
dateToParse 12-21-2021
finalDate undefined (several times)

I've also tried to run the function in a useEffect...

useEffect(() => {
    parseDateWithDashes(lastUpdateDate);
});

But that's an invalid hook call.

What am I doing wrong? How to fix that?

I resolved it this way.

I added the parsing to the thunk. And stringified in order to avoid non-serialized errors:

    const parsedDate = parse(lastUpdateDate, 'MM-dd-yyyy', new Date());
    dispatch(setLastUpdateDate(JSON.stringify(parsedDate)));

Then I just formatted it in the component:

export const convertStringDateToDate = (date: string) => {
    let finalDate;
    try {
        finalDate = JSON.parse(date);
        finalDate = format(parseISO(finalDate), 'E LLL d yyyy');
    } catch (e) {
        finalDate = 'loading date';
    }

    return finalDate;
};

That works

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