从特定日期开始的几天/一周前,使用Moment.js

编程入门 行业动态 更新时间:2024-10-24 16:29:02
本文介绍了从特定日期开始的几天/一周前,使用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()方法 ,它可以返回days,weeks,months,hours,minutes,..中两个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="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="cdnjs.cloudflare/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

更多推荐

从特定日期开始的几天/一周前,使用Moment.js

本文发布于:2023-11-27 05:12:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636739.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:几天   日期   js   Moment

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!