-1

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
    }

Dharmisha Doshi
  • 137
  • 3
  • 9
  • The use of *Date.parse* in `new Date(Date.parse(date))` is redundant. Also note that `new Date('2021-12-03')` will be parsed as UTC, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Feb 02 '22 at 22:13

3 Answers3

2

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);


const d2 = date.replace(/(\d{2})(\d{2})(\d{4})/,'$3-$2-$1');
console.log(d2);
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

You could convert the date in your sql query:

SELECT TO_CHAR(dateColumn, 'yyyy-mm-dd') AS formattedDate FROM ...
gue-ni
  • 44
  • 1
  • 3
  • Hi this is the query I am using `return (await this._permanent.findAll({ where: { data_date:date } })).map((term) => ({}}` Where can I add here? Thanks – Dharmisha Doshi Feb 02 '22 at 20:42
0

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)