如何在Ionic4中显示像6h前格式的日期时间

问题描述 投票:-2回答:1

在我的数据库时间商店,如2019-02-14 06:13:03如何在6小时前或2天前的甲酸显示。我正在使用laravel api。

3d前或18h前

ionic-framework laravel-5.7 ionic4
1个回答
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项目。

© www.soinside.com 2019 - 2024. All rights reserved.