Search code examples
angulardate-pipe

Extend predefined Angular date pipe formats with only month with year localized format (e.g 05/2020 for 'en' or 05.2020 in 'de' locale)


I need to extend the list of predefined angular date pipe formats (you can see it here) with format that consists of only month with year, e.g 05/2020 for 'en' or 05.2020 for 'de', that have to be localized. Is there any correct way to do this? I know that it is possible to create your own pipe and extend with some needed format, but when I indicate format e.g. 'MM/yyyy' it will format every date for every locale with that format, but I need to have it localized, so I need to add my custom formatting to already existing functionality.

I have an idea to do this with moment.js and not to use angular date pipe, the other idea is to manually remove the day from string that already have been localized (I agree quite stupid idea), but I am running out of ideas actually.

Any easy way? or other approach have to be defined here?


Solution

  • I had this problem, most simple solution that I found was, to create shared service method, that returns string of date format by the localization

    getDateFormat(format?: 'full' | 'short'): string {
            if (format === 'full') {
                return this.translateService.currentLang === 'en'
                    ? 'MMM dd, yyyy, HH:mm:ss'
                    : 'dd. MMM yyyy, HH:mm:ss';
            }
            if (format === 'short') {
                return this.translateService.currentLang === 'en'
                    ? 'MMM dd, yyyy'
                    : 'dd. MMM yyyy';
            }
        }
    

    I have here more formats, than one, but you could easily just make it with one, just checking what language is user using:

    getDateFormat(): string {
      return this.translateService.currentLang === 'en' 
        ? 'MMM dd, yyyy, HH:mm:ss'
        : 'dd. MMM yyyy, HH:mm:ss';
    )
    

    UPDATE:

    As I am having more experience, wanted to share a bit different approach for situations when you have more than a few language:

    getDateFormat(): string {
      const formatsByLocale = {
        'en': 'MMM dd, yyyy, HH:mm:ss'
      }
      const format = formatsByLocale[this.translateService.currentLang]
      return format || 'dd. MMM yyyy, HH:mm:ss';
    )
    

    Idea is that you could hold a lot of different locales with different formats and accessing those with same currentLang property, without specifying language. This makes it more reusable and readable in my opinion. By the way || symbol is for when there is no format, it would use default one, whatever comes after that symbol.