从特定日期开始的几天/一周前,使用Moment.js [英] Days/Weeks ago from specific date with Moment.js

查看:520
本文介绍了从特定日期开始的几天/一周前,使用Moment.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 moment.js ,例如,我有3个不同的日期.

I work with moment.js and I have 3 different dates, e.g.

  • 2018年7月30日
  • 2018年6月12日
  • 10.05.2018

我现在尝试计算从这些日期到今天(如果少于7天以前)或今天到几周(如果超过7天以前)之间的天数,并将其分成几个跨度.

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.

更新 感谢托马斯!

我得到了:

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

});

我还需要什么:

  • 不显示初始日期,仅显示"3 Days".如果它删除了结果",则我要工作了.

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

未显示"7 weeks 2 days",应为"7 weeks"

这是实际的> 小提琴 .

Here is the actual fiddle.

推荐答案

您可以使用momentjs diff()方法 ,它可以返回daysweeksmonthshoursminutes,..中两个dates之间的差. .根据您传递给它的选项.

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.

这应该是您的代码:

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

演示:

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

<span class="timestamp">30.07.2018 00:00</span>
<span class="timestamp">12.06.2018 00:00</span>
<span class="timestamp">10.05.2018 00:00</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

这篇关于从特定日期开始的几天/一周前,使用Moment.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆