【问题标题】:Pipe with MomentJS not returning correct difference of time带有 MomentJS 的管道未返回正确的时间差
【发布时间】:2018-02-05 22:24:40
【问题描述】:

我在 Ionic(Angular) 中构建了一个管道,它可以将时间转换为“从现在开始的时刻”。

这是我正在使用的地方:

 dateOfEvent = '2018-02-05 19:45:40';

 <p>{{dateOfEvent | timeago}}</p>

预期输出:40 分钟前

返回输出:2 小时前

这是我的烟斗

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
moment.locale('pt-br');

@Pipe({
  name: 'timeago',
})
export class TimeagoPipe implements PipeTransform {

  transform(value) {

      let timeAgo = moment(value).fromNow();
      return timeAgo;


  }
}

你能看出我做错了什么吗?

【问题讨论】:

  • 对我来说很好用!你能在结果中看到一个恒定的模式吗? (例如,实际输出总是比预期的早 80 分钟)
  • 是的@mok,实际输出总是2小时前。我已将语言环境设置为 br,看起来它使用不同的语言环境进行比较。你能帮我解决吗?

标签: angular ionic3 momentjs


【解决方案1】:

刚刚对此进行了修复。我不知道这是否是最好的方法,但如果有人有更好的方法,请在此处发布,我会更改最佳答案。

我所做的只是将dateOfEvent 格式化为一个矩值。

然后我根据格式化的值得到timeAgo,而不是直接来自数据库的那个(我的数据库中的那个也是由时刻生成的,但不知何故它在从数据库中检索时没有被识别为时刻)

所以修正后的管道是:

transform(value) {

      let formatted = moment().format(value);
      let timeAgo = moment(formatted).fromNow();

      return timeAgo;

}

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2020-11-15
    • 1970-01-01
    • 2017-05-28
    相关资源
    最近更新 更多