如何计算到下个月的第二天?
How to calculate to second day of the next month?
对于单元测试,我需要持续时间,直到下一个月的第二天。
例子:
今天 => 2018 年 1 月 20 日
下个月的第二天 => 2. 2018 年 2 月
我需要什么:到 2018 年 2 月 2 日为止的时间(以毫秒为单位)
您可以计算到月末的时差,然后在计算的时间末尾再增加 2 天的毫秒数 (2*((60000*60)*24)
)。我提供了一种通用方法,它允许您对给定月份的第 n<sup>th</sup>
天执行此计算:
const get_next_nth = n => today =>
today.getDate() < n-1 ?
(n-(today.getDate()+1))*60000*60*24 :
(new Date(today.getFullYear(), today.getMonth() + 1, 0) - today) + n*((60000*60)*24);
const get_next_second = get_next_nth(2);
const res = get_next_second(new Date());
console.log(res); // m/s until next 2nd date
console.log(new Date(new Date().getTime() + res).toDateString()); // string version of next 2nd date
您可以使用 moment.js 和流程来解决这个问题。
- 先找第二个月。
let nextMonth = moment(new Date()).add(1, "M").toDate(); ==> Wed Oct 02 2019 18:24:31 GMT+0600
- 查找月初。
let startOfMonth = moment(nextMonth).startOf("month").toDate(); ==> Tue Oct 01 2019 00:00:00 GMT+0600
- 查找该月的第二天。
let secondDay = moment(startOfMonth).add(1, "d").toDate(); ==> Wed Oct 02 2019 00:00:00 GMT+0600
对于单元测试,我需要持续时间,直到下一个月的第二天。 例子: 今天 => 2018 年 1 月 20 日 下个月的第二天 => 2. 2018 年 2 月
我需要什么:到 2018 年 2 月 2 日为止的时间(以毫秒为单位)
您可以计算到月末的时差,然后在计算的时间末尾再增加 2 天的毫秒数 (2*((60000*60)*24)
)。我提供了一种通用方法,它允许您对给定月份的第 n<sup>th</sup>
天执行此计算:
const get_next_nth = n => today =>
today.getDate() < n-1 ?
(n-(today.getDate()+1))*60000*60*24 :
(new Date(today.getFullYear(), today.getMonth() + 1, 0) - today) + n*((60000*60)*24);
const get_next_second = get_next_nth(2);
const res = get_next_second(new Date());
console.log(res); // m/s until next 2nd date
console.log(new Date(new Date().getTime() + res).toDateString()); // string version of next 2nd date
您可以使用 moment.js 和流程来解决这个问题。
- 先找第二个月。
let nextMonth = moment(new Date()).add(1, "M").toDate(); ==> Wed Oct 02 2019 18:24:31 GMT+0600
- 查找月初。
let startOfMonth = moment(nextMonth).startOf("month").toDate(); ==> Tue Oct 01 2019 00:00:00 GMT+0600
- 查找该月的第二天。
let secondDay = moment(startOfMonth).add(1, "d").toDate(); ==> Wed Oct 02 2019 00:00:00 GMT+0600