我正在尝试获取相对于当前时间的天数,仅返回以天为单位的天数。因此,如果某事发生在一周前,它会说 7 天。如果它发生在 2 个月前,它也会以天为单位返回那个时间。
我知道如何到达那里,但我无法将各个部分组合在一起。
我将我的日子作为数据属性“data-order”,所以 data-order="2019-4-2 00:00"或 "2019-4-2"如果它使计算更容易的话。
$(".pop-cal").each(function (i, obj) {
moment.relativeTimeThreshold("m", 1);
moment.relativeTimeThreshold("d", 25 * 100);
var date = $(this).attr("data-order");
var momentDate = moment(date).fromNow();
$(this).attr("data-content", momentDate);
});
这是让我约会,但他们总是关闭。
我的预期结果将类似于使用谷歌搜索并说“58 天前”并得到 2019 年 2 月 12 日星期二的确认。
我目前得到的结果是在“2019-2-12”创建的时刻“59 天前”。
最佳答案
如果您需要确切的天数,则 fromNow
方法不适合,因为 it works by将时间转换为 Duration(以月和毫秒为单位),然后将 Duration 转换为人类可读的形式(humanize 方法)。
作为Duration docs状态:
It is much better to use moment#diff for calculating days or years between two moments than to use Durations.
如果您在相隔 1 天的 2 月 28 日和 3 月 1 日执行 fromNow
,但给出相隔 4 天的 fromNow
(由于 28 天二月而不是 31 天)。
moment("2019-03-01").fromNow() // "45 days ago"
moment("2019-02-28").fromNow() // "49 days ago"
moment#diff method可以为您提供几天中两个时刻之间的确切差异,例如在时刻 a
和 b
之间:
a.diff(b, 'days')
关于javascript - 如何使用 momentjs 在几天内计算从现在开始的相对日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55638628/