简体   繁体   中英

How to convert Number to Date Using date-fns

I m trying to convert number into Date using date-fns.

Current: 20220211 or '20220211' (May be number or string)

Expected: Fri 11Feb

date-fns takes Date as an argument. First you should convert your string date value to a valid Date instance. Date could take several types of value, including ISO 8601 date standard, which means you could pass 2022-02-22 string value to Date constructor and it will be valid.

If your string format is not going to change your could do this:

const dateStr = '20220211';
const year = dateStr.slice(0,4);
const month = dateStr.slice(4,6);
const day = dateStr.slice(6,8);
const date = new Date(`${year}-${month}-${day}`);

And then use date in date-fns

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