Count days until today moment.js

38,554

Solution 1

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.

Solution 2

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.

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 each method can only act on data that is already in the DOM. So be sure to put it after you call 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

Share:
38,554

Related videos on Youtube

simple
Author by

simple

Updated on May 08, 2020

Comments

  • simple
    simple almost 4 years

    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; });
        }
    };
    
    • T.J. Crowder
      T.J. Crowder almost 11 years
      "I am using moment.js to write and format the date from JSON data and I think it is causing a conflict." Why do you think that? Calculating the date and outputting it are completely unrelated operations.
    • Alex Wayne
      Alex Wayne almost 11 years
      @alex23 There are lots of reasons to use a date library. Date/time math is ugly, and full of edge cases (variable month lengths, timezones, daylight savings, leap years).
    • simple
      simple almost 11 years
      When I put the date into the html manually, it works. When I data-bind it into the html, it does not work.
    • T.J. Crowder
      T.J. Crowder almost 11 years
      That calculation makes me feel a bit twitchy. Not all days have 24 hours, some have 23, others have 25 (and other such weirdness). You have a time-of-day on now but not on dateEnd (it's at midnight), which will further skew the results. Between the two, I wouldn't be 100% sure that the Math.round sorts it out for you...
    • T.J. Crowder
      T.J. Crowder almost 11 years
      "When I put the date into the html manually, it works. When I data-bind it into the html, it does not work." Demonstrate that in code/markup in the question (and also in the fiddle -- I don't see any data binding there -- but not just there).