Home > Net >  How can I require date format "yyyy-mm-dd" without parsing and reformatting?
How can I require date format "yyyy-mm-dd" without parsing and reformatting?

Time:02-01

I am using PostGreSql which contains date column in one of the table 2021-12-03T00:00:00.000Z. I developed API using nodejs to get the data from tables.

Below is the function I wrote to format the date and pass to the class. This works perfectly fine and I recieve 2021-12-03 as output

    formatDate(date) {
        var d = new Date(date),
            month = ''   (d.getMonth()   1),
            day = ''   (d.getDate()   1),
            year = d.getFullYear();
    
        if (month.length < 2) 
            month = '0'   month;
        if (day.length < 2) 
            day = '0'   day;
    
        return [year, month, day].join('-');
    }

    async getData(date){

        return {
            DataLine: await this._dateLine.getData1(d)
        }
    }

app.js

class Data extends Model {

    constructor(conn, schema) {
        super(conn, schema, "data", {
           
            Date: date(true),
            number: integer(true),  
          ...many other column
        }, true);
    }

    async getData1(date) {
        return (await this._permanent.findAll({ where: { td:date } })).map((term) => ({
            td: term.transDate,
            number: term.number,
        }));
    }
}

Is there a way to require them in the "yyyy-mm-dd" format to begin with and not parsing /reformatting as I did above ?

CodePudding user response:

One of the easiest ways to get yyyy-mm-dd is new Date().toISOString().split('T')[0]

CodePudding user response:

If you just want the local date as YYYY-MM-DD then toLocaleDateString with language 'en-CA' works:

console.log(new Date().toLocaleDateString('en-CA'));

  •  Tags:  
  • Related