我正在使用 Moment.js,我需要创建一个 for 循环,将特定天数添加到名为 theDate
的日期变量中,因此 'theDate'
持续以半个月的顺序推进(每月两次)。
此示例适用于向 dueDate 添加一天(一天)
for (var i = 1; i <= 10; i++) {
moment(theDate).add(i, 'day').add(1,'day');
console.log(dueDate);
}
如果'theDate'
设置为18.Jan.2017
,那么上面将打印以下内容:
1/18/17
1/19/17
1/20/17
1/21/17
1/22/17
...
我需要弄清楚如何添加天数(或周等),因此结果是以半月(每月两次)的顺序添加天数。这意味着,如果我的开始日期设置为 2017 年 1 月 18 日
,则 2017
全年的结果应如下所示:
1/18/17
2/01/17
2/18/17
3/04/17
3/18/17
4/01/17
4/18/17
5/02/17
5/18/17
6/01/17
6/18/17
7/02/17
7/18/17
8/01/17
8/18/17
9/01/17
9/18/17
10/02/17
10/18/17
11/01/17
11/18/17
12/02/17
12/18/17
请注意,我并不是在寻找我们通常在薪水支票中看到的第 1 种和第 15 种解决方案。我需要根据开始日期每月两次付款,该日期可以是用户决定设置的任何日期。
最佳答案
编辑根据您的回答,我调整了代码以进行优化,使其更加清晰并使其开箱即用。
for (var i = 0; i < 24; i++) {
var finalDate = moment([2017, 0, 31]).add(Math.ceil(0.5 * i), 'month');
if (i % 2 !== 0) {
finalDate.subtract(2, 'weeks');
}
console.log(finalDate.format("YYYY/MM/DD"));
}
这准确地输出:
2017/01/31
2017/02/14
2017/02/28
2017/03/17
2017/03/31
2017/04/16
2017/04/30
2017/05/17
2017/05/31
2017/06/16
2017/06/30
2017/07/17
2017/07/31
2017/08/17
2017/08/31
2017/09/16
2017/09/30
2017/10/17
2017/10/31
2017/11/16
2017/11/30
2017/12/17
2017/12/31
2018/01/17
请注意,用 moment 添加半个月即可添加一整月。为了使这种行为更加明显,我明确进行了四舍五入。
基于假设的原始答案
如果您希望用户认为每半月一次,您可以选择用户选择的日期,并据此自行设置第二个日期。
如果用户选择第 23 天,则添加 15,如果超过 28 天(当然)则换行,并将第二个日期设置为每月的 10 天。
由于每个月都有两个固定日期,因此您无需再添加天数。您只需添加一个月即可。就这么简单:
var userChosenDate = 23,
// if the user chose 28 and higher, just use 28 as a starting point.
yourChosenPaymentDate = (Math.min(userChosenDate, 28) + 15) % 28,
firstPayment = Math.min(userChosenDate, yourChosenPaymentDate),
secondPayment = Math.max(userChosenDate, yourChosenPaymentDate);
for (var i = 1; i <= 12; i++) {
console.log(i + "/" + firstPayment + "/2017");
console.log(i + "/" + secondPayment + "/2017");
}
使用 momentJs:
var userChosenDate = 23,
yourChosenPaymentDate = (Math.min(userChosenDate, 28) + 15) % 28,
firstPayment = moment(Math.min(userChosenDate, yourChosenPaymentDate) + "/1/2017", "D/M/YYYY"),
secondPayment = moment(firstPayment)
.date(Math.max(userChosenDate, yourChosenPaymentDate)),
format = "MM/DD/YYYY";
console.log(firstPayment.format(format));
console.log(secondPayment.format(format));
for (var i = 1; i < 12; i++) {
console.log(firstPayment.add(1, 'month').format(format));
console.log(secondPayment.add(1, 'month').format(format));
}
关于Javascript Moment.js 添加到最新日期(每月两次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39649399/