Count days until today moment.js

前端 未结 2 1715
温柔的废话
温柔的废话 2020-12-20 11:26

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 co

2条回答
  •  一整个雨季
    2020-12-20 11:55

    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.

提交回复
热议问题