繁体   English   中英

如何使用 Moment.js 获取今天和每月最后一天之间的天数?

[英]How do I get the days between the today's day and the last day of the month using Moment.js?

这是我现在拥有的代码:

  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');

我需要创建一个日历行,其中第一项是今天的日期,日历项的 rest 将是根据当前月份剩余的天数,因此我可以在 HTML 中渲染每一天Vue。

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

我认为 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>

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

 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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM