使用moment.js获取月底前的剩余天数

Get days left till end of the month with moment.js

本文关键字:余天 moment js 获取 使用      更新时间:2023-12-10

我想使用moment.js显示或隐藏一个链接,这取决于一个月内是否还有不到2周的时间,但我不确定正确的方法。

目前我有。。。

if (moment().endOf('month')<=(13, 'days'))
{
    //do link stuff here
}

但我认为这不是正确的做法。无论如何,它肯定什么都不做。有人能给我什么建议吗?提前谢谢。

您可以这样做:

var a = moment().endOf('month');
var b = moment();
if(a.diff(b, 'days') <= 13)
{
    //do something
}

如果您正在寻找纯javascript版本,我已经编写了以下函数:

function getMonthDaysLeft(){
    date = new Date();
    return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate() - date.getDate();
}

也许这样的东西会有所帮助。

const d = moment();
const currentDay = d.get("date");
const daysInMonth = d.daysInMonth();
const remainingDays = daysInMonth - currentDay;
console.log(remainingDays <= 13)