[英]Days/Weeks ago from specific date with Moment.js
I work with moment.js and I have 3 different dates, eg我使用moment.js并且我有 3 个不同的日期,例如
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.我现在尝试获取从这些日期到今天(如果它小于 7 天前)或直到今天的几周(如果它大于 7 天前)之间的天数差异,并将其放置在几个跨度中。
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;
});
});
What I still need:我还需要什么:
Not showing the initial date, just showing "3 Days"
.不显示初始日期,只显示"3 Days"
。 If it delete "result", I want work anymore.如果它删除“结果”,我就不想再工作了。
Not showing "7 weeks 2 days"
, this should just be "7 weeks"
不显示"7 weeks 2 days"
,这应该只是"7 weeks"
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.您可以使用 momentjs diff()
方法执行此操作,该方法可以根据您传递给它的选项以days
、 weeks
、 months
、 hours
、 minutes
返回两个dates
之间的差异。
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; } 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 has fromNow() function that returns "x days" or "x hours ago" from current date/time. Moment.js 有 fromNow() 函数从当前日期/时间返回“x 天”或“x 小时前”。
moment([2007, 0, 29]).fromNow(); // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.