我使用 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
发布评论