uniapp开发小程序—根据生日日期计算年龄周岁
- 软件开发
- 2025-08-15 12:09:02

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 class="age">{{getAge(info.birth)}}岁</view> methods: { //出生日期转化为年龄 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 } }, } 完成~uniapp开发小程序—根据生日日期计算年龄周岁由讯客互联软件开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“uniapp开发小程序—根据生日日期计算年龄周岁”