【问题标题】:How do I get the days between the today's day and the last day of the month using Moment.js?如何使用 Moment.js 获取今天和每月最后一天之间的天数?
【发布时间】:2022-01-13 17:23:57
【问题描述】:

这是我现在拥有的代码:

  const moment = require('moment')
    const m = moment


    const currDay = m().format('D')
    const dayOfWeek = m().format('dddd')
    const daysInMonth = m().daysInMonth()

    const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
    const endOfMonth   = moment().endOf('month').format('YYYY-MM-DD hh:mm');

我需要创建一个日历行,其中第一项是今天的日期,其余日历项将是根据当前月份剩余的天数,因此我可以在两者之间呈现每一天我使用 Vue 编写的 HTML。

示例:周三 8、周四 9、周五 10 ... 周五 31。

【问题讨论】:

    标签: javascript arrays vue.js date momentjs


    【解决方案1】:

    我认为 OP 被过早格式化的常见错误绊倒了。 format 可以很好地看到中间结果,但这样做会产生一个不利于额外计算的字符串。

    尽量只处理日期对象。仅当您必须:(a) 呈现给人类读者,或 (b) 序列化以进行存储或传输时才转换为字符串。

    在不格式化的情况下工作...

    const daysRemainingThisMonth = moment().endOf('month').diff(moment(), 'days');
    console.log(`There are ${daysRemainingThisMonth} days remaining this month`)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

    【讨论】:

      【解决方案2】:

      就像 POJS 等价物一样,如果您有一个函数可以返回该月的最后一天,您可以使用它并获取两个日期之间的差异,例如

      function getMonthEnd(date = new Date()) {
        return new Date(date.getFullYear(), date.getMonth() + 1, 0);
      }
      
      function getMonthDaysLeft(date = new Date()) {
        return getMonthEnd(date).getDate() - date.getDate();
      }
      
      let d = new Date();
      console.log(`There are ${getMonthDaysLeft(d)} days left in ${d.toLocaleString('en',{month:'long'})}.`);

      要获得剩余天数的列表/数组,只需循环一个日期,一次添加 1 天,然后将所需格式的日期写入列表:

      function getMonthDaysLeftAsList(date = new Date()) {
        let d = new Date(+date);
        // Formatter
        let f = new Intl.DateTimeFormat('en',{
          day: 'numeric',
          month: 'short'
        });
        let m = d.getMonth();
        let dayList = [];
        while (d.getMonth() == m) {
          dayList.push(f.format(d));
          d.setDate(d.getDate() + 1);
        }
        return dayList;
      }
      
      console.log(getMonthDaysLeftAsList());

      【讨论】:

        猜你喜欢
        • 2018-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-28
        • 2019-03-04
        • 2012-04-14
        • 1970-01-01
        相关资源
        最近更新 更多