【工具方法】getAge
williamzhou 4/2/2021 面试编程能力
# 参考资料
# 问题
根据出生年月计算年龄
- 约定: 过了 x 岁生日后一天才算 x 岁
注意事项:
- 参数合法性校验
- 边界条件
- UTC时间
# 代码实现
/**
* @param {String} birthday 出生年月日
* @returns {Number} 年龄
*/
function getAge(birthday) {
const validator = new RegExp(/^\d{4}-\d{2}-\d{2}$/)
if (!validator.test(birthday)) {
throw new Error(`invalid argument ${birthday}`)
}
const [birthYear, birthMonth, birthDay] = birthday.split('-').map(str => Number(str))
const now = new Date()
const nowYear = now.getFullYear()
const nowMonth = now.getMonth() + 1
const nowDay = now.getDate()
const age = nowYear - birthYear - 1
if (nowMonth > birthMonth || (nowMonth === birthMonth && nowDay > birthDay)) {
return age + 1
} else {
return age
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 测试一下
var log = console.log
log(getAge('1995-09-12'))
log(getAge('1995-03-26'))
log(getAge('1995-03-27'))
log(getAge('1995-03-28'))
1
2
3
4
5
2
3
4
5