最近在写一个项目要求计算周岁,并且判断相应条件后作出提示语,折腾两天觉得周岁挺恶心人的(对于菜菜的我来说哟!)。废话不多说上代码!
// 周岁计算方法 将日期传入形参(chargeYear)后就可以使用,我这里是vue项目
ageFun(chargeYear) {
var date = new Date(this.maxDate);
var date2 = new Date(this.timeValue);
var nTime = date.getTime() - date2.getTime();
var day = Math.floor(nTime / 1000 / 86400);
// // 生日日期
let newBirthday = new Date(this.timeValue).getTime();
let nowYear = new Date(newBirthday).getFullYear();
let nowMonth = new Date(newBirthday).getMonth() + 1;
let nowDay = new Date(newBirthday).getDate();
let birthdayText = nowYear + "-" + nowMonth + "-" + nowDay;
var returnAge = getNowAge(birthdayText);
console.log("年龄是", returnAge);
// 至某时的周岁年龄
// @param birthday: 格式"yyyy-MM-dd"字符串
// @param toDate: 格式"yyyy-MM-dd"字符串
function getAge(birthday, endDate) {
var birthdayDate = stringToDate(birthday);
var toDate = stringToDate(endDate);
var age = 0;
age = toDate.getFullYear() - birthdayDate.getFullYear();
if (
toDate.getMonth() * 100 + toDate.getDate() <
birthdayDate.getMonth() * 100 + birthdayDate.getDate()
) {
age--;
}
return age;
}
// 将"yyyy-MM-dd"格式的字符串转换为日期
// @param dateString
// @returns {Date}
function stringToDate(dateString) {
return new Date(dateString.replace(/-/g, "/"));
}
function getNowAge(birthday) {
var nowDate = dateToString(new Date());
return getAge(birthday, nowDate);
}
function dateToString(date) {
return (
date.getFullYear() +
"-" +
padDate(date.getMonth() + 1) +
"-" +
padDate(date.getDate())
);
}
function padDate(d) {
d = d + "";
if (d.length == 1) {
return "0" + d;
} else {
return d;
}
}
if (chargeYear == "1") {
if (day < 28 || returnAge > 65) {
return requestRemind("该产品投保年龄范围为:28天-65周岁");
}
}
if (chargeYear == "5" || chargeYear == "10") {
if (day < 28 || returnAge > 60) {
return requestRemind("该产品投保年龄范围为:28天-60周岁");
}
}
if (chargeYear == "15") {
if (day < 28 || returnAge > 55) {
return requestRemind("该产品投保年龄范围为:28天-55周岁");
}
}
if (chargeYear == "20") {
if (day < 28 || returnAge > 50) {
return requestRemind("该产品投保年龄范围为:28天-50周岁");
}
}
if (chargeYear == "30") {
if (day < 28 || returnAge > 40) {
return requestRemind("该产品投保年龄范围为:28天-40周岁");
}
}
console.log("天数是", day);
// 调用接口方法
this.$nextTick(() => {
this.getData();
});
},
最后希望可以帮到每一个和我一样的码农。知识是日积月累的,就像一盆水,接满需要把水龙头得水调小,是一个道理。着急只会被溅一身