Days/Weeks ago from specific date with Moment.js

Max*_*mpo 1 javascript jquery date momentjs

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 7 days ago) or the weeks until today (if it more than 7 days ago) and place it in several spans.

UPDATE thanks Thomas!

I got:

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

        let date = moment(html, "DD.MM.YYYY HH:mm", true), 
        now = moment(),
        days = Math.floor(Math.abs(date - now) / 86400000), 
        weeks = Math.floor(days/7),
        result = date.format("DD.MM.YYYY") + " - ";

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

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

      return result;
    });

});
Run Code Online (Sandbox Code Playgroud)

What I still need:

  • Not showing the initial date, just showing "3 Days". If it delete "result", I want work anymore.

  • Not showing "7 weeks 2 days", this should just be "7 weeks"

Here is the actual fiddle.

cнŝ*_*ŝdk 6

你可以用momentjs做到这一点diff()的方法,它可以返回两者之间的区别datesdaysweeksmonthshoursminutes,...基于期权您传递给它。

这应该是您的代码:

days = now.diff(date, "days")
weeks = now.diff(date, "weeks")
Run Code Online (Sandbox Code Playgroud)

演示:

days = now.diff(date, "days")
weeks = now.diff(date, "weeks")
Run Code Online (Sandbox Code Playgroud)
$(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;
    } else if (days || weeks === 0) {
      result += days + (days === 1 ? " day" : " days");
    }

    result += '<br />';
    return result;
  });
});
Run Code Online (Sandbox Code Playgroud)


Nit*_*hav 5

Moment.js 有 fromNow() 函数从当前日期/时间返回“x 天”或“x 小时前”。

moment([2007, 0, 29]).fromNow();     // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years
Run Code Online (Sandbox Code Playgroud)