关于网站建设项目收取费用,网站 域名解析错误,电话销售-网站建设-开场白,如何制作网站策划书0、需求
在UniApp开发小程序中#xff0c;将接口返回的出生日期转化为年龄#xff1b;判断接口返回的年龄是否是周岁
可以使用JavaScript的日期处理方法来实现。
一、第一种方式#xff08;示例代码#xff09;#xff1a;
//javascript
// 假设接口返回的年龄为生日的…0、需求
在UniApp开发小程序中将接口返回的出生日期转化为年龄判断接口返回的年龄是否是周岁
可以使用JavaScript的日期处理方法来实现。
一、第一种方式示例代码
//javascript
// 假设接口返回的年龄为生日的日期字符串如 1990-01-01
const birthday 1990-01-01;const now new Date(); // 获取当前日期
const birthDate new Date(birthday); // 将生日字符串转换为日期对象
const ageDiff now.getFullYear() - birthDate.getFullYear(); // 计算年龄差值// 如果生日还未过则年龄减1
if (now.getMonth() birthDate.getMonth() || (now.getMonth() birthDate.getMonth() now.getDate() birthDate.getDate())) {ageDiff--;
}
console.log(ageDiff); // 输出31// 判断年龄是否是周岁
const isFullAge ageDiff 1;
console.log(isFullAge); // 输出true二、第二种方式
view classage{{getAge(info.birth)}}岁/viewmethods: {//出生日期转化为年龄getAge(val){let currentYear new Date().getFullYear() //当前的年份let calculationYear new Date(val).getFullYear() //计算的年份const wholeTime currentYear val.substring(4) //周岁时间const calculationAge currentYear - calculationYear //按照年份计算的年龄//判断是否过了生日if (new Date().getTime() new Date(wholeTime).getTime()){return calculationAge}else {return calculationAge - 1}},
}
完成~