-6

I have the following class where I specify a Date type for the birtDate.

When I create an instance of the class, and I fill the date in the following way, this is what I get on the front-end: Sun Jun 17 2012 00:00:00 GMT+0200 (CEST)

I only want the Jun 17 2012part, so what format should I provide in order to get that ?

The class:

export class Person {
    public firstname: String;
    public lastname: String;
    public birthDate: Date;
    public area: String;
    public rating: number[];
}

An instance of the class:

   {
      firstname: 'Elin',
      lastname: 'Skuladottir',
      birthDate: new Date(2012, 5, 17),
      area: 'Greater Copenhagen',
      rating: []
    }
CodeHip
  • 367
  • 5
  • 18
  • save the birthDate as you wish, use date pipe to show it https://angular.io/api/common/DatePipe. (personally, I think that the use of moment.js is in case you need "operate" with dates, if only you want to show it's not necesary. – Eliseo Mar 01 '18 at 15:54
  • NOTE: better birthDate:new Date('2012-05-17") than birthDate:new Date(2012,5,17) -you can have problems with GTM zones - – Eliseo Mar 01 '18 at 15:55

2 Answers2

0

You can use toLocaleDateString to format the Date.

try with this function:

   
function formatDate(date) {
 var options = { year: 'numeric', month: 'short', day: 'numeric' };
 return date.toLocaleDateString('en-US', options).replace(/,/g,'');
}

var person = {
  firstname: 'Elin',
  lastname: 'Skuladottir',
  birthDate: new Date(2012, 5, 17),
  area: 'Greater Copenhagen',
  rating: []
}
    
    
console.log(formatDate(person.birthDate));
gabrielperales
  • 6,935
  • 1
  • 20
  • 19
0

Nothing beats Moment.js in operations related to Dates
Take a look at the Moment.js docs that makes the following code tick

let obj = {
  firstname: 'Elin',
  lastname: 'Skuladottir',
  birthDate: new Date(2012, 5, 17),
  area: 'Greater Copenhagen',
  rating: []
};

// ddd: Sun
// MMM: Jun
// DD: 17
// YYYY: 2012
console.log(moment(obj.birthDate).format("ddd MMM DD YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Don't forget to include the Moment.js cdn into your index.html

Abhijit Kar ツ
  • 1,732
  • 1
  • 11
  • 24