show-date.pipe.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { Injectable, Pipe, PipeTransform } from '@angular/core';
  2. import { formatDate } from '@angular/common';
  3. import { registerLocaleData } from '@angular/common';
  4. import localeZh from '@angular/common/locales/zh';
  5. registerLocaleData(localeZh);
  6. @Pipe({
  7. name: 'showDate'
  8. })
  9. @Injectable()
  10. export class ShowDatePipe implements PipeTransform {
  11. transform(date: Date, locale: string = 'zh-CN'): string {
  12. if (!date) {
  13. return '';
  14. }
  15. const now = new Date();
  16. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  17. const yesterday = new Date(today);
  18. yesterday.setDate(yesterday.getDate() - 1);
  19. const beforeYesterday = new Date(yesterday);
  20. beforeYesterday.setDate(beforeYesterday.getDate() - 1);
  21. const dateOnly = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  22. if (dateOnly.toISOString() === today.toISOString()) {
  23. return formatDate(date, 'HH:mm', locale);
  24. } else if (dateOnly.toISOString() === yesterday.toISOString()) {
  25. return `昨天 ${formatDate(date, 'HH:mm', locale)}`;
  26. } else if (dateOnly.toISOString() === beforeYesterday.toISOString()) {
  27. return `前天 ${formatDate(date, 'HH:mm', locale)}`;
  28. } else {
  29. return formatDate(date, 'yyyy-MM-dd HH:mm', locale);
  30. }
  31. }
  32. }