JS Date技术问询:如何计算距百年诞辰时长?setFullYear()使用遇阻
嘿,这两个问题其实都有很清晰的解决思路,我给你一步步拆解:
一、计算距百年诞辰的剩余时长
首先,我们得先明确百年诞辰的日期——就是你的生日日期加上100年。然后用这个日期减去当前时间,再把差值转换成你需要的年、月、日、时、分格式就行。不过要注意,直接相减可能会出现负数(比如当前日期的月份比诞辰月份小),所以得处理借位逻辑。
具体实现代码:
// 1. 解析输入的生日日期(示例:"1/1/1980") const inputBirthDate = "1/1/1980"; const [month, day, year] = inputBirthDate.split("/").map(Number); // 注意:JavaScript的月份是0-based(0=1月,11=12月),所以要减1 const birthDate = new Date(year, month - 1, day); // 2. 计算百年诞辰日期 const centenaryDate = new Date(birthDate); centenaryDate.setFullYear(birthDate.getFullYear() + 100); // 3. 获取当前时间 const now = new Date(); // 4. 计算各单位的剩余时长,处理借位 let remainingYears = centenaryDate.getFullYear() - now.getFullYear(); let remainingMonths = centenaryDate.getMonth() - now.getMonth(); let remainingDays = centenaryDate.getDate() - now.getDate(); let remainingHours = centenaryDate.getHours() - now.getHours(); let remainingMinutes = centenaryDate.getMinutes() - now.getMinutes(); // 分钟借位 if (remainingMinutes < 0) { remainingMinutes += 60; remainingHours -= 1; } // 小时借位 if (remainingHours < 0) { remainingHours += 24; remainingDays -= 1; } // 日期借位(需要获取上一个月的总天数) if (remainingDays < 0) { const prevMonthLastDay = new Date(now.getFullYear(), now.getMonth(), 0).getDate(); remainingDays += prevMonthLastDay; remainingMonths -= 1; } // 月份借位 if (remainingMonths < 0) { remainingMonths += 12; remainingYears -= 1; } // 5. 输出结果 if (remainingYears < 0) { console.log("已经过了百年诞辰啦!"); } else { console.log(`距百年诞辰还有:${remainingYears}年${remainingMonths}个月${remainingDays}天${remainingHours}小时${remainingMinutes}分钟`); }
关键点说明:
- 用
new Date(birthDate)复制生日日期,避免修改原对象 - 借位逻辑是从最小单位(分钟)到最大单位(年)依次处理,确保每个单位的数值都是非负的
- 计算上一个月的天数时,用
new Date(year, month, 0)会自动返回该月最后一天的日期,非常方便
二、处理时分的加减操作
其实getHours()和getMinutes()返回的都是数字,你完全可以直接加减,但更省心的是用Date对象自带的setHours()和setMinutes()方法——它们会自动处理进位/借位,根本不用你手动算!
示例代码:
const now = new Date(); console.log("当前时间:", now.toLocaleString()); // 1. 加2小时30分钟 now.setHours(now.getHours() + 2); now.setMinutes(now.getMinutes() + 30); console.log("加2h30m后:", now.toLocaleString()); // 2. 减3小时40分钟 const anotherNow = new Date(); anotherNow.setMinutes(anotherNow.getMinutes() - 40); anotherNow.setHours(anotherNow.getHours() - 3); console.log("减3h40m后:", anotherNow.toLocaleString());
为什么用set方法更靠谱?
比如你给setMinutes()传70,它会自动转换成1小时10分钟,同时把小时数加1;如果减分钟后变成负数,它会自动从小时里借1小时(60分钟),甚至小时不够借时,会自动把日期减1天,小时加24。完全不用你写复杂的判断逻辑!
内容的提问来源于stack exchange,提问作者Daeron
相关产品推荐
相关产品推荐

