数天直到今天moment.js [英] Count days until today moment.js

查看:111
本文介绍了数天直到今天moment.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能,可以获得直到今天的天数。但它工作正常,我使用moment.js来编写和格式化JSON数据的日期,我认为这会导致冲突。有没有办法用moment.js做同样的事情?

I have a function that gets the number of days until today. It works however, I am using moment.js to write and format the date from JSON data and I think it is causing a conflict. Is there a way to do the same thing using moment.js?

这是有效的JavaScript: http://jsfiddle.net/infatti/XeqPT/

This is the working JavaScript: http://jsfiddle.net/infatti/XeqPT/

// Count days due
function daysUntil(year, month, day) {
  var now = new Date(),
      dateEnd = new Date(year, month - 1, day), // months are zero-based
      days = (dateEnd - now) / 1000/60/60/24;   // convert milliseconds to days

  return Math.round(days);
}

如何使用moment.js完成同样的事情?

How can the same thing be done using moment.js?

如果有兴趣的话,这就是我在不工作日期的方式。

If interested, here is how I am pulling in the date when it does not work.

<span class="due-date" data-bind="textualDate: DueDate"></span>

ko.bindingHandlers.textualDate = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
        var textContent = moment(valueUnwrapped).format("MM/DD/YYYY");
        ko.bindingHandlers.text.update(element, function () { return textContent; });
    }
};


推荐答案

如果您遇到的问题是使用 moment.js 获取两个日期之间的持续时间,然后您可以使用 diff 这样的函数:

If the problem you have is to use moment.js to get the duration between two dates, then you can use the diff function like this:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
var diffInMs = a.diff(b); // 86400000 milliseconds
var diffInDays = a.diff(b, 'days'); // 1 day

现在,我不知道你是否对KnockoutJS有任何问题,但是这个应该确保你的计算是用 moment.js 完成的。

Now, I don't know if you have any problem with KnockoutJS, but this should ensure that your computation is done with moment.js.

为了你的兴趣,我自己做了一个自定义绑定处理程序来显示片刻日期前一段时间。与你的不同之处在于我的观察力已经是一个时刻的对象。所以,我在这里对其进行了修改以使其适用于标准日期对象:

Just for your interest, I made myself a custom binding handler for displaying a moment date some time ago. The difference with yours is that my observable was already a moment object. So, I've modified it down here to make it work with standard date objects:

    ko.bindingHandlers.moment = {
        update: function(element, valueAccessor) {
            var value = valueAccessor();
            var formattedValue = moment(ko.utils.unwrapObservable(value)).format('MM/DD/YYYY');
            $(element).text(formattedValue);
        }
    };

编辑:我给你一个小提示示例。

I made you a fiddle with the example.

这篇关于数天直到今天moment.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆