JavaScript 转换格式不规范日期实现已过期开放房源信息隐藏
解决步骤
1. 核心逻辑说明
你只需要把提取到的日期字符串补全年份后转成标准Date对象,再和今日日期做纯日期维度的对比即可,下面的方案已经兼容你提到的年末跨年场景。
2. 完整可运行代码
// 你的原有逻辑 const str = 'Public: Thu Feb 11, 10:00AM-2:00PM'; const opdate = str.substr(8); // 第一步:切割掉时间部分,只保留日期段 const pureDateStr = opdate.split(',')[0]; const now = new Date(); const currentYear = now.getFullYear(); // 第二步:补全年份并转Date对象 let targetDate = new Date(`${pureDateStr} ${currentYear}`); // 兼容跨年场景:如果拼接当前年后得到的日期比现在晚超过10个月,说明是上一年的日期 if (targetDate.getTime() - now.getTime() > 10 * 30 * 24 * 60 * 60 * 1000) { targetDate = new Date(`${pureDateStr} ${currentYear - 1}`); } // 第三步:清除两个日期的时间部分,只对比年月日 const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const openHouseDate = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate()); // 第四步:判断是否过期 const isExpired = openHouseDate < today; // 过期就隐藏房源 if (isExpired) { // 此处写你的隐藏房源逻辑 console.log('房源已过期,隐藏'); }
3. 细节说明
- 跨年判断的10个月阈值可以根据你的业务灵活调整,只要覆盖12月到次年1月的时间差即可,避免把去年12月的日期错误识别成今年12月
- 两个日期都把时间重置为0点,避免当天的时间早晚影响判断,符合你只需要比较日期的需求
内容的提问来源于stack exchange,提问作者Joey Lawrence
相关产品推荐
相关产品推荐

