【问题标题】:How to calculate to second day of the next month?如何计算到下个月的第二天?
【发布时间】:2019-09-02 11:09:52
【问题描述】:

对于单元测试,我需要持续时间,即到每月第二天的持续时间。 例子: 今天 => 2018 年 1 月 20 日 次日第二天 => 2018 年 2 月 2 日

我需要什么:2018 年 2 月 2 日之前的毫秒数

【问题讨论】:

  • 如果日期是1. Feb 2018,那么第二天“每月的第二天”将是2. Feb 2018,还是应该是2. Mar 2018
  • 2. 2018 年 2 月。我有一个在每个月的第二天运行的 cron 作业。为了测试,我必须确保它工作正常
  • 好吧,如果日期是2. Feb 2018,它应该计算到当前日期的时间,还是下一个日期2. Mar 2018的时间?
  • 2. 2018 年 3 月将是完美的,但如果 cronjob 也在 2.2 触发,则并不重要

标签: javascript unit-testing mocha.js sinon chai


【解决方案1】:

你可以使用moment.js和流动的流程来解决这个问题。

  1. 首先找到第二个月。

let nextMonth = moment(new Date()).add(1, "M").toDate(); ==> Wed Oct 02 2019 18:24:31 GMT+0600

  1. 查找月初。

let startOfMonth = moment(nextMonth).startOf("month").toDate(); ==> Tue Oct 01 2019 00:00:00 GMT+0600

  1. 求一个月的第二天。

let secondDay = moment(startOfMonth).add(1, "d").toDate(); ==> Wed Oct 02 2019 00:00:00 GMT+0600

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      相关资源
      最近更新 更多