Search code examples
angulardatepickercalendarprimeng

How to format date when using primeng calendar?


How to get only date,month and year when using Prime NG p-calendar component? i got these value when i do console.log my variable. It showed this value :

Date {Wed Feb 01 2017 00:00:00 GMT+0700 (SE Asia Standard Time)}

So i don't want it that long, i just need 01/02/2017, i don't need the rest. So how can i get date,month and year format? since i already did this :

here is my html :

and here is my component.ts :

export class report {

  public date: any;


  constructor() {

  }

  public proses(date) {

    console.log(date);

  }

}

Solution

  • You can do this using pure JavaScript Date functions like this:

    let day = date.getDate();
    let month = date.getMonth() + 1; // add 1 because months are indexed from 0
    let year = date.getFullYear();
    
    console.log(day + '/' + month + '/' + year);
    

    The other way is using the toLocaleDateString() method like this:

    let newDate = date.toLocaleDateString();
    console.log(newDate);
    

    Or you can use some library as i.e. moment.js which you can use in the following way:

    let newDate = moment(date).format('DD/MM/YYYY').toString();
    console.log(newDate();
    

    Both solutions will console log the same string.