ngx-date-fns

repository·master·Indexed 41 days ago

https://github.com/joanllenas/ngx-date-fns

A collection of Angular pipes that wrap the date-fns library for date formatting, parsing, and manipulation within Angular templates. Version 12.0.1 requires date-fns v4.x.x and Angular >= v17.0.0. Includes a wide range of pipes for formatting, differences, additions, and boolean checks, with support for both pure and impure pipes to handle runtime locale changes via DateFnsConfigurationService.

Tokens
7.6K
Snippets
29
Records
36
Agent score
50%

What's inside ngx-date-fns

  1. Understand pure vs impure pipes in ngx-date-fns

    master

    In ngx-date-fns, most pipes are pure by default. However, some pipes are marked as impure.

    An impure pipe may depend on external state (like the current time or locale) and will be re-evaluated on every change detection cycle. If you need a version of an impure pipe that does not depend on external state (and thus behaves as a pure pipe), look for the Pure suffix in the pipe name (e.g., dfnsFormatPure instead of dfnsFormat).

  2. Choosing between pure and impure pipes

    master

    Locale-aware pipes in ngx-date-fns come in two flavors: pure and impure. Choosing the right one depends on how you manage your application's locale.

    • Use pure pipes if you set the locale only once when the application starts. Pure pipes are more performant because they do not listen for locale changes.
    • Use impure pipes if you need to change the locale at runtime (e.g., via a language switcher). Impure pipes are kept in memory and listen for notifications from DateFnsConfiguration.setLocale(locale: Locale), allowing them to re-render when the locale changes. This comes with a slight memory and performance overhead.
  3. Install ngx-date-fns for older date-fns versions

    master

    If your project uses an older version of date-fns, use the corresponding version of ngx-date-fns:

    date-fns v3

    npm install --save date-fns@3.6.0
    npm install --save ngx-date-fns@11.0.1

    date-fns v2

    npm install --save date-fns@2.30.0
    npm install --save ngx-date-fns@10.0.1

    Note: For date-fns v2, it is recommended to use v2.16.1 or >= v2.21.1 to avoid broken tree shaking.

    date-fns v1

    npm install --save date-fns@1.29.0
    npm install --save ngx-date-fns@4.0.3
  4. How to change the locale at runtime

    master

    You can change the default locale dynamically during application execution by injecting DateFnsConfigurationService into your component and calling .setLocale(locale).

    import { Component } from '@angular/core';
    import { es, de } from 'date-fns/locale';
    import { DateFnsConfigurationService, DateFnsModule } from 'ngx-date-fns';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [DateFnsModule],
      template: `
        <p>{{ dateOne | dfnsFormat: 'EEE LLLL d yyyy' }}</p>
        <hr />
        Set default locale to: 
        <a href="#" (click)="changeToGerman()">German</a>, 
        <a href="#" (click)="changeToSpanish()">Spanish</a>.
      `
    })
    export class App {
      dateOne = new Date(2016, 0, 1);
      constructor(public config: DateFnsConfigurationService) {}
    
      changeToGerman() {
        this.config.setLocale(de);
      }
    
      changeToSpanish() {
        this.config.setLocale(es);
      }
    }
  5. How to change the locale globally

    master

    Instead of passing a locale to every pipe via an options object, you can set a global default by providing a custom DateFnsConfigurationService in your application configuration.

    1. Create an instance of DateFnsConfigurationService.
    2. Use .setLocale(locale) to set your desired locale.
    3. Provide it in your appConfig using the DateFnsConfigurationService token.
    // app.config.ts
    import { ApplicationConfig } from '@angular/core';
    import { DateFnsConfigurationService } from 'ngx-date-fns';
    import { fr } from 'date-fns/locale';
    
    const frenchConfig = new DateFnsConfigurationService();
    frenchConfig.setLocale(fr);
    
    export const appConfig: ApplicationConfig = {
      providers: [{ provide: DateFnsConfigurationService, useValue: frenchConfig }]
    };
  6. Install ngx-date-fns

    master

    To use ngx-date-fns, you must also install date-fns. The installation command depends on the version of date-fns you are using. The latest version of ngx-date-fns requires date-fns v4.x.x and Angular >= v17.0.0.

    Latest Version (date-fns v4)

    npm install --save date-fns
    npm install --save ngx-date-fns
  7. How locale precedence works in ngx-date-fns

    master

    The library uses a hierarchical approach to determine which locale to use for date formatting. When using a pipe, the locale is resolved in the following order of precedence:

    1. Pipe Options: If you pass a specific locale in the pipe's arguments (e.g., {{ date | date: 'PPP' : { locale: es } }}), that locale is used.
    2. Global Configuration: If no locale is provided in the pipe options, the library falls back to the locale configured in the DateFnsConfigurationService via setLocale().
    3. Default: If neither is provided, it falls back to the standard date-fns default behavior.
  8. Configure the global locale using DateFnsConfigurationService

    master

    To set a global locale for all ngx-date-fns pipes and utilities in an Angular application, instantiate DateFnsConfigurationService, use the setLocale() method with a locale object from date-fns/locale, and provide the instance in your application configuration using the { provide: DateFnsConfigurationService, useValue: ... } pattern.

    import { DateFnsConfigurationService } from 'ngx-date-fns';
    import { fr } from 'date-fns/locale';
    
    const frenchConfig = new DateFnsConfigurationService();
    frenchConfig.setLocale(fr);
    
    export const appConfig: ApplicationConfig = {
      providers: [
        { provide: DateFnsConfigurationService, useValue: frenchConfig }
      ]
    };
  9. Basic Usage of ngx-date-fns pipes

    master

    To use the pipes, import DateFnsModule into your Angular component or module. You can then use various dfns* pipes in your templates to format, parse, or manipulate dates.

    Example usage in a standalone component:

    import { CommonModule } from '@angular/common';
    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    import { es } from 'date-fns/locale';
    import { DateFnsModule } from 'ngx-date-fns';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule, DateFnsModule],
      template: `
        <p>{{ dateOne | dfnsFormat: 'MM/dd/yyyy' }}</p>
        <p>{{ [dateOne, dateTwo] | dfnsMin | dfnsFormat: 'EEE LLLL d yyyy' }}</p>
        <p>
          {{ dateThree | dfnsFormatDistanceToNow: options }} - (Explicit 'es' locale)
        </p>
      "
    })
    export class App {
      dateOne = new Date(2016, 0, 1);
      dateTwo = new Date(2017, 0, 1);
      dateThree: Date;
      options = {
        locale: es,
        addSuffix: true
      };
    
      constructor() {
        this.dateThree = new Date();
        this.dateThree.setDate(this.dateThree.getDate() - 6);
      }
    }
    
    bootstrapApplication(App);
  10. Use the dfnsWeekdayName pipe

    master

    The dfnsWeekdayName pipe converts a weekday number into its name.

    Parameters

    • WeekdayNameFormat (optional): Controls the length/format of the name.
      • x1: One character (e.g., 'M')
      • x2: Two characters (e.g., 'Mo')
      • x3: Three characters (e.g., 'Mon')
      • full: Full name (e.g., 'Monday'). Defaults to full.
    • Locale (optional): An optional date-fns Locale object to localize the output.
    <div>
      <!-- Prints Monday -->
      {{ 0 | dfnsWeekdayName }}
    </div>
    <div>
      <!-- Prints Mon -->
      {{ 0 | dfnsWeekdayName : 'x3' }}
    </div>