Greg-A
Greg-A

Reputation: 852

Bad date format with format ()

I have a date format following:

2019-02-12T09:29:34

and I would like to transform it in the following way

Tuesday 12 February 2019

For that I use a function:

public formatDate(date: string): string {
   const DateChange: string = new Date(date).toString()
    return format(DateChange, 'EEEE, d MMMM, yyyy');
  }

called like this:

{{formatDate(history.dateTraitement)}}

Unfortunately out I find myself with this format the:

On 2222, 2 February, yyyy

Where is the problem?

Upvotes: 1

Views: 63

Answers (2)

Reza
Reza

Reputation: 19843

Assuming you have defined data variable like below

date: Date = new Date('2019-02-12T09:29:34');

You have two ways as below

1 - using angular pipe in your html as

{{date | date:'fullDate'}}

2 - using angular pipe in your code (and add DatePipe in providers of your module)

  dateString: string = '';

  constructor(private datePipe: DatePipe) {
    this.dateString = this.datePipe.transform(this.date, 'fullDate')
  }

Please see this working example here

Note: You date string has some space in the time part, I assume that is typo and is not in your real data

See other format options (or to create your custom) here

Upvotes: 3

bryan60
bryan60

Reputation: 29315

angular exposes the formatDate function used by it's own date pipe, which you may want to consider using, if the date pipe doesn't work for you and you aren't in a context where dependency injection is easy:

import {formatDate} from '@angular/common';

formatDate(myDate, 'full', 'en-US');

arg 1 is the date (date obj or string), arg 2 is the format (either short hand or custom), and arg 3 is the locale (normally angular figures this out for you, but you must supply when using directyl)

however, since you're using this in template, your best bet is honestly the date pipe angular already gives you.

Upvotes: 1

Related Questions