从现在开始的字符串显示更新时间

时间:2017-09-29 09:00:55

标签: javascript momentjs

我正在使用fromNow()方法。

moment.updateLocale("en", {
  relativeTime: {
    s: "seconds",
    m: "a minute",
    mm: "%d minutes",
    h: "an hour",
    hh: "%d hours",
    d: "a day",
    dd: "%d days",
    M: "a month",
    MM: "%d months",
    y: "a year",
    yy: "%d years"
  }
});


let value = "2017-09-29T10:50:00.000000+0100";
let dateDisplay = moment(value).fromNow();
//this logs in an hour although it is in 50 mins
console.log(dateDisplay);

我相信这是预期的,因为在上面提供的链接上的文档中指出45-89分钟将显示an hour ago

有没有人知道如何更新它以便它可以在实际时间工作 - 即50 minutes ago/in 50 minutes? (取决于时间是否过去或将来)

1 个答案:

答案 0 :(得分:0)

您可以使用relativeTimeThreshold

正如文档所说:

  

$ids = explode(',',$this->settings['showMainSponsor']) foreach($ids as $key => $id){ $partners[$id] = $this->partnerRepository->findByUid($id); } 具有阈值,用于定义单位何时被视为分钟,一小时等等。例如,默认情况下,超过45秒被视为一分钟,超过22小时被视为一天,依此类推。要更改这些截止值,请使用duration.humanize,其中单位是moment.relativeTimeThreshold(unit, limit)smhd之一。

在您的情况下,您可以使用M。这是一个现场样本:

moment.relativeTimeThreshold('m', 60);
let value = "2017-09-29T11:00:00.000000+0100";
let dateDisplay = moment(value).fromNow();
console.log(dateDisplay);

moment.updateLocale("en", {
  relativeTime: {
    s: "seconds",
    m: "a minute",
    mm: "%d minutes",
    h: "an hour",
    hh: "%d hours",
    d: "a day",
    dd: "%d days",
    M: "a month",
    MM: "%d months",
    y: "a year",
    yy: "%d years"
  }
});

moment.relativeTimeThreshold('m', 60);

dateDisplay = moment(value).fromNow();
//this logs in an hour although it is in 50 mins
console.log(dateDisplay);