【问题标题】:How to display date-time like 6h ago format in Ionic4如何在 Ionic4 中显示 6 小时前格式的日期时间
【发布时间】:2019-03-04 05:10:26
【问题描述】:

在我的数据库时间存储中,例如 2019-02-14 06:13:03 如何以 6 小时前或 2 天前的格式显示。我正在使用 laravel api。

3d 前或 18 小时前

【问题讨论】:

标签: ionic-framework laravel-5.7 ionic4


【解决方案1】:

第一步在某处创建管道,您的代码将是

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'timeAgo' })
export class TimeAgo implements PipeTransform {
  transform(d: any): string {

    let currentDate = new Date(new Date().toUTCString());
    let date = new Date(d + "Z");

    let year = currentDate.getFullYear() - date.getFullYear();
    let month = currentDate.getMonth() - date.getMonth();
    let day = currentDate.getDate() - date.getDate();
    let hour = currentDate.getHours() - date.getHours();
    let minute = currentDate.getMinutes() - date.getMinutes();
    let second = currentDate.getSeconds() - date.getSeconds();

    let createdSecond = (year * 31556926) + (month * 2629746) + (day * 86400) + (hour * 3600) + (minute * 60) + second;

    if (createdSecond >= 31556926) {
      let yearAgo = Math.floor(createdSecond / 31556926);
      return yearAgo > 1 ? yearAgo + " years ago" : yearAgo + " year ago";
    } else if (createdSecond >= 2629746) {
      let monthAgo = Math.floor(createdSecond / 2629746);
      return monthAgo > 1 ? monthAgo + " months ago" : monthAgo + " month ago";
    } else if (createdSecond >= 86400) {
      let dayAgo = Math.floor(createdSecond / 86400);
      return dayAgo > 1 ? dayAgo + " days ago" : dayAgo + " day ago";
    } else if (createdSecond >= 3600) {
      let hourAgo = Math.floor(createdSecond / 3600);
      return hourAgo > 1 ? hourAgo + " hours ago" : hourAgo + " hour ago";
    } else if (createdSecond >= 60) {
      let minuteAgo = Math.floor(createdSecond / 60);
      return minuteAgo > 1 ? minuteAgo + " minutes ago" : minuteAgo + " minute ago";
    } else if (createdSecond < 60) {
      return createdSecond > 1 ? createdSecond + " seconds ago" : createdSecond + " second ago";
    } else if (createdSecond < 0) {
      return "0 second ago";
    }
  }
}

然后在 app.component.ts 中包含 timeAgo 管道,类似于:

declarations: [
      AppComponent,
      TimeAgo,
      ...,
    ],

之后,您的 html 代码将类似于

<p>{{timeValue | timeAgo}}</p>

我在这里为你创建了Stackblitz 项目。

【讨论】:

  • 我使用了你的代码,但它给出了类似的错误(找不到管道'timeAgo')。如何消除这个错误请帮助我。
  • 您没有正确提供您的 TS 文件路径。你能告诉我像 src/app/timeAgo.ts 这样的路径吗? na d确保你在 app.module.ts 文件中注入了 timeAgo 管道
  • 我的ts路径就像src/app/time-ago.pipe.ts
  • 那么请在 app.module.ts 中导入你的文件import { TimeAgoPipe } from './time-ago.pipe';。请参考这个link
  • 我是这样使用的,但是在 html 中使用时会报错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
相关资源
最近更新 更多