Home > database >  convert string value to date format TS
convert string value to date format TS

Time:06-11

I defined my variable as string

startedStringDate:string;

I want to convert string value to date format. My startedStringDate value is like this

startedStringDate='2022/05/01';

How could i convert it to date format

CodePudding user response:

I'd you date-fns for this, specifically the parse function: https://date-fns.org/v2.28.0/docs/parse

CodePudding user response:

Since your date format uses / as seperators, you need to split it before turning it into a Date-Object. You also need to subtract 1 from the month, since the Date constructor expects a zero-based value (where January = 0, February = 1, March = 2, etc.)

const [year, month, day] = str.split('/');

const date = new Date( year,  month - 1,  day);
  • Related