11

How can I get the format, as a string, used by Angular to display dates ? I use the date pipe after setting LOCALE_ID in my app.module.

Now I'd like to retrieve the "dd/mm/yyyy" string, to put in my input placeholders.

Basically, what's described here but for Angular.

Thanks

[edit]

To make it more explicit, I'm not looking for a way to format dates, that's already done (with the native date pipe). I want the string that represents the format being used by this pipe.

Because I'd like my datepicker placeholder to be like

"Date (format: XXXXXX)"

and I want the "XXXXXX" part to be correct (i.e. "jj/mm/aaaa" for french, "mm/dd/yyyy" for english)

Valentin Coudert
  • 1,759
  • 3
  • 19
  • 44
  • I am not clear what you mean but [moment](https://momentjs.com/) might help you. – nightElf91 Dec 07 '17 at 08:40
  • I've edited my post. I hope there is an Angular native way of doing this – Valentin Coudert Dec 07 '17 at 08:45
  • you are never gonna get a translated string like "jj/mm/aaaa", best you can possibly get is "dd/mm/yyyy" for your french example. The "english" format string is in the LDML data (@angular/common/locales), so in theory you should be able to extract that information somehow, but what use is it in english? Personally I would just add the placeholder as a string and include it in my translation files. – Pevara Dec 07 '17 at 09:01
  • I want a more generic way of getting this string because we will handle many languages, and we don't know their format, we'll trust Angular on that point (I'm ok with having 'dd/mm/yyyy' for french) – Valentin Coudert Dec 07 '17 at 09:17

2 Answers2

20

I hope that in the meantime you've come across getLocaleDateFormat() and getLocaleTimeFormat(). (Angular 6)

import { getLocaleDateFormat, FormatWidth } from '@angular/common';
export class Foobar {
  constructor( @Inject( LOCALE_ID ) private locale: string ) { }

  private getDateFormat() {
    return getLocaleDateFormat( this.locale, FormatWidth.Short );
  }
}
Simon
  • 2,994
  • 3
  • 28
  • 37
2

If you want to declaratively format a date within your template:

{{ today | date: 'dd/MM/yyyy' }}

If you want to imperatively get the formatted date within code:

import { DatePipe } from '@angular/common';
// in your component class
var date = new DatePipe().transform(today, 'dd/MM/yyyy')
Michael Kang
  • 52,003
  • 16
  • 103
  • 135