Home > front end >  Javascript -How can I convert DDMMYYYY to format (YYYY-MM-DD)?
Javascript -How can I convert DDMMYYYY to format (YYYY-MM-DD)?

Time:02-03

In my project I have PostgreSql table which contain date (Data type date)column. The date received from column is being passed to getData function.

I am getting output in format 03122021, which I want to convert in format 2021-12-03 (YYYY-MM-DD) DATE ONLY. How can I make the conversion?

 async getData(date){
         console.log("date is ", date);     ---->>> date is 03122021
        const d = new Date(Date.parse(date));
        console.log('d', d)                  ---->> d Invalid Date
    }

CodePudding user response:

So parse the sting into a format it recognizes

const date = '03122021'
const d = new Date(date.replace(/(\d{2})(\d{2})(\d{4})/,'$2/$1/$3'));
console.log(d);

CodePudding user response:

You could convert the date in your sql query:

SELECT TO_CHAR(dateColumn, 'yyyy-mm-dd') AS formattedDate FROM ...

CodePudding user response:

I know this is not perfect answer but if you get this type of value alltime , then you can do this

const dateValue = '03122021'
let day = dateValue.substring(0,2)
let month = dateValue.substring(2,4)
let year = dateValue.substring(4,8)
const date =`${year}-${month}-${day}`
console.log(date)
  •  Tags:  
  • Related