使用TypeScript(JavaScript)判断用户今年是否将年满18岁
嘿,我完全get到你的需求了——你要的是一个能判断某人今年内会年满18岁的函数,哪怕现在离他的生日还有几天(甚至几小时),只要生日在今年,就返回true;如果得等到明年才满18,就返回false。之前的代码可能只处理了“当前是否已经满18”的情况,对吧?我来帮你把思路理清楚,再给出可行的实现。
核心逻辑拆解
其实这个问题的关键就是判断此人的18岁生日是否落在当前年份的范围内,不管当前日期是在生日之前还是之后:
- 先计算出此人满18岁的具体日期(出生日期年份+18,月、日保持不变)
- 再判断这个18岁生日的日期是否在今年的1月1日到12月31日之间
只要满足这个条件,就返回true,否则返回false。
JavaScript实现示例
function willTurn18ThisYear(birthDate) { // 把输入的出生日期转为Date对象 const birth = new Date(birthDate); const currentYear = new Date().getFullYear(); // 计算18岁生日的日期(注意月份是0-based,0代表1月) const eighteenthBirthday = new Date( birth.getFullYear() + 18, birth.getMonth(), birth.getDate() ); // 定义今年的起始和结束日期 const startOfCurrentYear = new Date(currentYear, 0, 1); const endOfCurrentYear = new Date(currentYear, 11, 31); // 判断18岁生日是否在今年范围内 return eighteenthBirthday >= startOfCurrentYear && eighteenthBirthday <= endOfCurrentYear; }
Python实现示例
如果你用Python的话,思路是一样的,代码会更简洁:
from datetime import date def will_turn_18_this_year(birth_date): current_year = date.today().year # 计算18岁生日 eighteenth_birthday = date(birth_date.year + 18, birth_date.month, birth_date.day) # 定义今年的起止日期 start_of_year = date(current_year, 1, 1) end_of_year = date(current_year, 12, 31) # 判断区间 return start_of_year <= eighteenth_birthday <= end_of_year
测试验证
举几个例子帮你确认逻辑是否正确:
- 假设当前是2024年5月10日,迈克的生日是2006年5月15日:18岁生日是2024年5月15日,在今年范围内 → 返回
true - 迈克的生日是2007年5月15日:18岁生日是2025年5月15日,不在今年 → 返回
false - 迈克的生日是2006年3月1日:18岁生日是2024年3月1日,虽然已经过了,但仍在今年 → 返回
true - 迈克的生日是2005年5月15日:18岁生日是2023年5月15日,不在今年 → 返回
false
这样写的话,就完全符合你要的需求啦,不管当前日期是在生日前还是后,只要今年内会满18,就返回true。
内容的提问来源于stack exchange,提问作者BlueCat
相关产品推荐
相关产品推荐

