0

THE SITUATION:

From the API i get the dates in the european format: 01-06-2018
That is: day - month - year (1 june 2018).

I need to display in a more beautiful way - the 'd MMM y' format is exactly what I need.

But if i use the pipeline in the view in this way:

{{ projectInfo.project_start_date | date: 'd MMM y' }}

The result is: 6 Jan 2018 (while in my case should be 1 Jun 2018)

Because it thinks that the first two cyphers of my date 01-06-2018 are the month - while they are days..

THE QUESTION:

How can convert European formatted dates in Angular 2?

Should I convert them in the component from European format to American format?

If yes - do you know how that can be done in Angular 2?

Thanks!

EDIT:

This how I have tried to convert the string i received from the API into an actual date:

In the component:

dateTest: Date;
this.dateTest = new Date(this.projectInfo['project_start_date']);

In the view:

<span> {{ dateTest | date: 'd MMM y' }} </span>

The result:

Still the same: 6 Jan 2018

PLUNKER:

https://plnkr.co/edit/ZYMoaoxawVCtScUZfL3B?p=preview

FrancescoMussi
  • 20,760
  • 39
  • 126
  • 178
  • I think the problem stays in the projectInfo.project_start_date. Is it a string or a Javascript Date? – Luca De Nardi Dec 01 '16 at 13:56
  • Because if it is a string, Angular would try to automatically convert it to a date and then format it. The problem is that Angular interprets the date in American format, that's where's the problem. In that case you would need to convert the strings into dates BEFORE processing them. – Luca De Nardi Dec 01 '16 at 13:59
  • I'm afraid you're gonna have to resort to a method like this: http://stackoverflow.com/a/4679696/2947592 – wvdz Dec 01 '16 at 14:00
  • or `var pattern = /(\d{2})\-(\d{2})\-(\d{4})/; var dt = new Date(dateString.replace(pattern,'$3-$2-$1'));` which works for european dates (euro dates only tho) – Ivar Reukers Dec 01 '16 at 14:03
  • Thanks for the hints. I have edited the question. The string is converted into a actual date - but is of course an american date. – FrancescoMussi Dec 01 '16 at 14:10
  • `isoDate = europeDate.split("-").reverse().join("-");` - from there you should be able to pass it in unambiguously. – Niet the Dark Absol Dec 01 '16 at 14:19
  • You're coing to need https://docs.angularjs.org/guide/i18n – realbart Dec 01 '16 at 14:20
  • @Rob Hey dude. Could you please reconsider removing the duplicate. Since this is a specific question regarding the european date format and in the context of Angular2. – FrancescoMussi Dec 01 '16 at 15:04

1 Answers1

0

All pipes seem to rely on the locale. Try to change it from your main module :

providers: [
    { provide: LOCALE_ID, useValue: "en-US" }, //replace "en-US" with your locale
     appRoutingProviders 
]

sources

Community
  • 1
  • 1
soywod
  • 4,377
  • 3
  • 26
  • 47