MomentJS如何构造动态当前年固定为08-15的日期
实现方案
你可以通过以下两种方式实现动态取当前年份、固定月日为08-15的需求:
方案1:字符串拼接(最简单直观)
直接获取当前年份后拼接为目标日期字符串即可:
const date = moment(person.indefiniteContractDate .toISOString() .substring(2), 'YY-MM-DD'); // 动态拼接当年8月15日的日期字符串 const compareDate = `${new Date().getFullYear()}-08-15`; if (date.isAfter(compareDate))
方案2:使用Moment API生成(更稳妥,避免格式问题)
直接通过Moment的方法生成目标日期对象,适配性更强:
const date = moment(person.indefiniteContractDate .toISOString() .substring(2), 'YY-MM-DD'); // 注意Moment中月份从0开始计数,8月对应参数为7,startOf('day')可将时分秒置为0避免时间误差 const compareDate = moment().month(7).date(15).startOf('day'); if (date.isAfter(compareDate))
内容的提问来源于stack exchange,提问作者pmiranda
相关产品推荐
相关产品推荐

