Home > Blockchain >  How to convert Number to Date Using date-fns
How to convert Number to Date Using date-fns

Time:02-24

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

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

Expected : Fri 11Feb

CodePudding user response:

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

  • Related