Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

javascript - Count days until today 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?

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);
}

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; });
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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);
        }
    };

Edit: I made you a fiddle with the example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...