问题描述
我有一个函数可以获取到今天的天数.但是,它有效,我使用 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.
为了您的兴趣,我为自己制作了一个自定义绑定处理程序,用于显示一段时间前的日期.与你不同的是,我的 observable 已经是一个 moment 对象.因此,我在此处对其进行了修改以使其适用于标准日期对象:
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);
}
};
我为您制作了一个fiddle 示例.
I made you a fiddle with the example.
这篇关于计算到今天的天数 moment.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!