环境:VUE
export default {
data() {
return {
age:'',
};
},
输入的Birth格式为yyyy/mm/dd,最终结果显示在age中。
methods: {
handleCompute(Birth) {
this.Birth = Birth;
// 获取当前日期
var currentDate = new Date();
// 设置出生日期
var birthDate = new Date(this.Birth);
// 计算年龄
var age = currentDate.getFullYear() - birthDate.getFullYear();
// 检查是否已经过了生日
var hasPassedBirthday = (currentDate.getMonth() > birthDate.getMonth()) ||
(currentDate.getMonth() === birthDate.getMonth() && currentDate.getDate() >= birthDate.getDate());
// 如果生日还没过就减去一岁
if (!hasPassedBirthday) {
age--;
}
// 输出年龄
this.age=age;
},
}