[英]How to get the week count from start date and end date using moment JS
How to get the week count from the start date and end date using moment JS. 如何使用矩JS从开始日期和结束日期获取周数。 Then I want to push it into an array.
然后我想将其推入数组。 If a week is more than one week, I want to show like this
const result = [1, 2, 3];
如果一周多于一周,我想显示如下
const result = [1, 2, 3];
const dateStart = moment(1517812701107).format('DD-MM-YYYY');
const dateEnd = moment(1518331101107).format('DD-MM-YYYY');
From this start date and end date I need to get the number for week array. 从这个开始日期和结束日期,我需要获取星期数组的编号。 Is it possible in
moment
JS. 有可能在
moment
JS。
First of all, you don't want to format your date just yet or you'll just have a string representation, not a moment instance. 首先,您现在不想格式化日期,否则将只具有字符串表示形式,而不是瞬间实例。 Once you've taken care of that it's as simple as using
diff
: 一旦解决了它,就和使用
diff
一样简单:
const dateStart = moment(1517812701107);
const dateEnd = moment(1518331101107);
const weeksBetween = dateEnd.diff(dateStart, 'weeks');
As for turning that into a progression array, you could simply loop through the result: 至于将其转换为进度数组,您可以简单地遍历结果:
const result = []
for (let i = 1; i <= weeksBetween; i++) {
result.push(i)
}
The timestamps you provided are less than a week apart and will result in 0
. 您提供的时间戳记相隔不到一周,并且结果为
0
。 If you are aiming to find the exact ratio, add a floating point flag for the third variable: 如果要找到确切的比率,请为第三个变量添加一个浮点标志:
dateEnd.diff(dateStart, 'weeks', true); // 0.8571428571428571
Source: https://momentjs.com/docs/#/displaying/difference/ 资料来源: https : //momentjs.com/docs/#/displaying/difference/
You can try diff function, Try the following code. 您可以尝试diff函数,请尝试以下代码。 Hope this helps.
希望这可以帮助。
const dateStart = moment(1507812701107);
const dateEnd = moment(1518331101107);
const result = Array(dateEnd.diff(dateStart, 'week')).fill().map((e,i)=>i+1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.