Skip to content Skip to sidebar Skip to footer

Days/weeks Ago From Specific Date With Moment.js

I work with moment.js and I have 3 different dates, e.g. 30.07.2018 12.06.2018 10.05.2018 I now try to get the difference in days from these dates until today (if it is less then

Solution 1:

You can do this with momentjs diff() method, which can return the difference between two dates in days, weeks, months, hours, minutes, ... based on the option you pass to it.

This is how should be your code:

now = moment()
days = now.diff(date, "days")
weeks = now.diff(date, "weeks")

Demo:

$(document).ready(function() {
  $('.timestamp').html((index, html) => {

    let date = moment(html, "DD.MM.YYYY HH:mm", true),
      now = moment(),
      days = now.diff(date, "days"),
      weeks = now.diff(date, "weeks"),
      result = "";

    if (weeks) {
      result += weeks + (weeks === 1 ? " week " : " weeks ");
      days = days % 7;
    } elseif (days || weeks === 0) {
      result += days + (days === 1 ? " day" : " days");
    }

    result += '<br />';
    return result;
  });
});
<spanclass="timestamp">30.07.2018 00:00</span><spanclass="timestamp">12.06.2018 00:00</span><spanclass="timestamp">10.05.2018 00:00</span><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Solution 2:

Moment.js has fromNow() function that returns "x days" or "x hours ago" from current date/time.

moment([2007, 0, 29]).fromNow();     // 4 years agomoment([2007, 0, 29]).fromNow(true); // 4 years

Post a Comment for "Days/weeks Ago From Specific Date With Moment.js"