| | |
| | | } |
| | | }, |
| | | /** |
| | | * 核心工具函数:根据生日字符串计算年龄 |
| | | * @param {string} birthdayStr - 生日字符串(支持 YYYY-MM-DD / YYYY/MM/DD) |
| | | * @returns {number} 周岁(-1 表示日期无效) |
| | | */ |
| | | calculateAgeFromBirthday(birthdayStr) { |
| | | console.log(birthdayStr,'、、、、、、、、、、’'); |
| | | if (!birthdayStr) return -1 |
| | | |
| | | // 1. 统一格式并精准解析生日(解决 1/26 这类无补零日期的解析问题) |
| | | const normalized = birthdayStr.replace(/[./]/g, '-') |
| | | console.log(normalized,'normalized’'); |
| | | const [birthYear, birthMonth, birthDay] = normalized.split('-').map(Number) |
| | | // 直接用数字创建 Date 对象,避免字符串解析的歧义(月份从 0 开始) |
| | | const birthDate = new Date(birthYear, birthMonth - 1, birthDay) |
| | | |
| | | // 2. 校验日期合法性 |
| | | if (isNaN(birthDate.getTime())) return -1 |
| | | // 反向验证:确保输入的年月日和 Date 对象一致(避免 2010/2/30 这类无效日期) |
| | | if ( |
| | | birthDate.getFullYear() !== birthYear || |
| | | birthDate.getMonth() + 1 !== birthMonth || |
| | | birthDate.getDate() !== birthDay |
| | | ) { |
| | | return -1 |
| | | } |
| | | |
| | | // 3. 获取当前日期(精准到日,排除时分秒干扰) |
| | | const now = new Date() |
| | | const currentYear = now.getFullYear() |
| | | const currentMonth = now.getMonth() + 1 // 转成 1-12 月 |
| | | const currentDay = now.getDate() |
| | | |
| | | // 4. 核心:精准计算周岁 |
| | | let age = currentYear - birthYear |
| | | // 判断:当前日期 < 生日日期 → 年龄减 1(只有当前日期 >= 生日日期,才满对应周岁) |
| | | if ( |
| | | currentMonth < birthMonth || // 月份没到 |
| | | (currentMonth === birthMonth && currentDay < birthDay) // 月份到了,但日期没到 |
| | | ) { |
| | | age-- |
| | | } |
| | | |
| | | // 5. 边界处理:年龄不能为负(排除未来生日) |
| | | return age |
| | | }, |
| | | /** |
| | | * 日期格式转时间戳 |
| | | * @param {Object} timeStamp |
| | | */ |