You need to enable JavaScript to run this app. MomentJS如何构造动态当前年固定为08-15的日期
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 00:00:03