jQuery 计算到今天的天数 moment.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16424702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:06:11  来源:igfitidea点击:

Count days until today moment.js

javascriptjqueryknockout.jsmomentjs

提问by simple

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?

我有一个函数可以获取到今天的天数。但是,它有效,我使用 moment.js 从 JSON 数据中编写和格式化日期,我认为它会导致冲突。有没有办法使用 moment.js 做同样的事情?

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

这是工作的 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);
}

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

如何使用 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; });
    }
};

回答by Jalayn

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

如果您遇到的问题是使用moment.js来获取两个日期之间的持续时间,那么您可以使用diff函数,如下所示:

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

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

现在,我不知道您是否对 KnockoutJS 有任何问题,但这应该确保您的计算是使用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:

只是为了您的兴趣,我为自己制作了一个自定义绑定处理程序,用于显示一段时间前的日期。与你不同的是,我的 observable 已经是一个 moment 对象。所以,我在这里修改了它以使其与标准日期对象一起使用:

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

Edit: I made you a fiddlewith the example.

编辑:我让你摆弄这个例子。

回答by CodeThug

Works for me - see this fiddle - http://jsfiddle.net/tlarson/sBMTn/5. It might be helpful if you could show us a fiddle where the problem exists so that we can see what's going on.

对我有用 - 看这个小提琴 - http://jsfiddle.net/tlarson/sBMTn/5。如果您可以向我们展示问题所在的小提琴,以便我们了解发生了什么,这可能会有所帮助。

Here is the code I added:

这是我添加的代码:

var viewModel = {
    firstDate: ko.observable("2013-7-1"),
    secondDate: ko.observable("2013-9-1")
};
ko.applyBindings(viewModel);

And I updated your markup to make use of the viewmodel:

我更新了您的标记以使用视图模型:

<div id="paging1">
    <ul class="list paging-items">
        <li><!-- item -->
            <h4>Due in <span class="days-due"></span> days</h4>

            <h4><span data-bind="textualDate: firstDate" class="due-date"></span></h4>
        </li><!-- #item -->
        <li><!-- item -->
            <h4>Due in <span class="days-due"></span> days</h4>

            <h4><span data-bind="textualDate: secondDate" class="due-date"></span></h4>
        </li><!-- #item -->
    </ul>
</div>

Note that your call to jQuery's eachmethod can only act on data that is already in the DOM. So be sure to put it after you call ko.applyBindings

请注意,您对 jQueryeach方法的调用只能作用于 DOM 中已有的数据。所以一定要在你打电话之后放ko.applyBindings

However...

然而...

You might want to consider using a computed rather than using jQuery for the 'Due in X days' part of the page. Here is how you could do that: http://jsfiddle.net/tlarson/sBMTn/1

对于页面的“X 天到期”部分,您可能需要考虑使用计算而不是使用 jQuery。你可以这样做:http: //jsfiddle.net/tlarson/sBMTn/1