import { Pipe } from '@angular/core';
import { formatDistanceToNow } from 'date-fns';
import enUS from 'date-fns/locale/en-US';
import zhCN from 'date-fns/locale/zh-CN';
import { NzI18nService } from 'ng-zorro-antd/i18n';

@Pipe({ name: 'dateDist' })
export class DateDist{

  // locale 自适应
  locale = zhCN;
  constructor(private i18n: NzI18nService) {
    if (this.i18n.getLocaleId() == 'en') this.locale = enUS;
  }

  /**
   * https://date-fns.org/v2.28.0/docs/format
   * @param date
   */
   transform(date: string | Date) {
    if (!date) return '';
    if (date instanceof Date) {
      // return formatDistanceToNow(date, {locale : zhCN});
      return formatDistanceToNow(date, {locale : this.locale});
    } else {
      // return formatDistanceToNow(new Date(date), {locale : zhCN});
      return formatDistanceToNow(new Date(date), {locale : this.locale});
    }

  }
}