show-date.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233
  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. const now = new Date();
  13. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  14. const yesterday = new Date(today);
  15. yesterday.setDate(yesterday.getDate() - 1);
  16. const beforeYesterday = new Date(yesterday);
  17. beforeYesterday.setDate(beforeYesterday.getDate() - 1);
  18. const dateOnly = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  19. if (dateOnly.toISOString() === today.toISOString()) {
  20. return formatDate(date, 'HH:mm', locale);
  21. } else if (dateOnly.toISOString() === yesterday.toISOString()) {
  22. return `昨天 ${formatDate(date, 'HH:mm', locale)}`;
  23. } else if (dateOnly.toISOString() === beforeYesterday.toISOString()) {
  24. return `前天 ${formatDate(date, 'HH:mm', locale)}`;
  25. } else {
  26. return formatDate(date, 'yyyy-MM-dd HH:mm', locale);
  27. }
  28. }
  29. }