Implementing ISO 8601 date time format in Angular
Implementing ISO 8601 date time format in Angular

In this post, I will show you how to Implement ISO 8601 date time format in Angular. Formatting a date-time in a client-side application like Angular is always a challenge.

Are you looking for an unambiguous calendar-and-clock format that is internationally understood? It’s time for ISO 8601.

From ISO.ORG

Read more about ISO 8601 DATE AND TIME FORMAT

What benefit do I get for ISO 8601?

ISO 8601 can be used by anyone who wants to use a standardized way of presenting:

  • Date
  • Time of day
  • Coordinated Universal Time (UTC)
  • Local time with offset to UTC
  • Date and time
  • Time intervals
  • Recurring time intervals

ISO 8601 date-time format Implementation

Let's create a generic HashTable to use as Key.

export interface HashTable {
  [key: string]: T;
}

Now, Let's create a Service for DateFormat as shown below

import { Injectable } from '@angular/core';
import { HashTable } from './hash-table';

type FormatFunc = (date: Date) => string;
@Injectable({
  providedIn: 'root'
})
export class DateFormat {
  formattingTokenFunc: HashTable = {};

  private formattingTokens = /(HH?|HH?|hh?|mm?|ss?|MM?|dd?|yy?y?y?|.)/g;

  constructor() {
    // add years function
    const getYearFunc = (date: Date) => date.getFullYear().toString();

    // Year, no leading zero (e.g. 2015 would be 15)
    this.addFormatToken('y', 0, (date: Date) =>
      (date.getFullYear() % 100).toString()
    );
    this.addFormatToken('yyy', 0, getYearFunc);
    this.addFormatToken('yyyy', 0, getYearFunc);
    // Year, leading zero (e.g. 2015 would be 015)
    this.addFormatToken('yy', 3, (date: Date) =>
      (date.getFullYear() % 100).toString()
    );

    // add months function
    const getMonthFunc = (date: Date) => (date.getMonth() + 1).toString();

    this.addFormatToken('M', 0, getMonthFunc);
    this.addFormatToken('MM', 2, getMonthFunc);

    // add day function
    const getDayFunc = (date: Date) => date.getDate().toString();

    this.addFormatToken('d', 0, getDayFunc);
    this.addFormatToken('dd', 2, getDayFunc);

    // add hours function
    const get12HrFunc = (date: Date) => (date.getHours() % 12).toString();

    // 12-hour clock, with a leading 0 eg (e.g. 06)
    this.addFormatToken('hh', 2, get12HrFunc);
    // 12-hour clock hour
    this.addFormatToken('h', 0, get12HrFunc);

    const get24HrFunc = (date: Date) => date.getHours().toString();

    this.addFormatToken('HH', 2, get24HrFunc);
    this.addFormatToken('H', 0, get24HrFunc);

    // add minute function
    const getMinFunc = (date: Date) => date.getMinutes().toString();
    this.addFormatToken('m', 0, getMinFunc);
    // Minutes with a leading zero
    this.addFormatToken('mm', 2, getMinFunc);

    // add seconds function
    const getSecFunc = (date: Date) => date.getSeconds().toString();
    this.addFormatToken('s', 0, getSecFunc);
    this.addFormatToken('ss', 2, getSecFunc);
  }

  formatToISO8601Date(date: Date | string): string {
    return this.format(date, 'yyyy-MM-dd');
  }

  format(date: Date | string, format: string): string {
    const finalDate = date instanceof Date ? date : new Date(date);

    const matches = format.match(this.formattingTokens);
    let result = '';

    matches.forEach(match => {
      // const hasFunc = this.formattingTokenFunc.hasOwnProperty('match');
      const formatFunc = this.formattingTokenFunc[match];

      result += formatFunc ? formatFunc(finalDate) : match;
    });

    return result;
  }

  prefixZero(length: number, input: string): string {
    return `${Math.pow(10, length)}${input}`.slice(-1 * length);
  }

  prefixZeroFunc(length: number, formatFunc: FormatFunc): FormatFunc {
    return (c: Date) => this.prefixZero(length, formatFunc(c));
  }

  private addFormatToken(
    token: string,
    addZeroesLength: number,
    // formatFunc: ((date: Date) => string)
    formatFunc: FormatFunc
  ): void {
    this.formattingTokenFunc[token] =
      addZeroesLength > 0
        ? this.prefixZeroFunc(addZeroesLength, formatFunc)
        : formatFunc;
  }
}
Implementing ISO 8601 date time format in Angular
Implementing ISO 8601 date time format in Angular

By Injecting this service at root level, any component or service in the Angular application can ask for it using DI and then make use of it.

How to consume DateFormat service

Let's say you have a variable for date and you need to initiate the date in ISO 8601 format.

@Component({
  selector: 'app-dateformat-example',
  templateUrl: './dateformat-example.component.html',
  styleUrls: ['./dateformat-example.component.css']
})
export class DateFormatExampleComponent implements OnInit {
effectiveDate: any;
constructor(
  private dateFormat: DateFormat) { }

  ngOnInit() {
    this.effectiveDate = this.dateFormat.formatToISO8601Date(new Date());
  }
}

Related Post

Conclusion

In this post, I showed Implementing ISO 8601 date time format in Angular. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights