uniapp开发小程序—根据生日日期计算年龄 & 周岁

0、需求

  1. 在UniApp开发小程序中,将接口返回的出生日期转化为年龄;
  2. 判断接口返回的年龄是否是周岁

可以使用JavaScript的日期处理方法来实现。

一、第一种方式(示例代码):

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
		}
	},
}

完成~

相关推荐
小徐_233318 小时前
uni-app 要停更了?我们把 Wot UI 搬到了 uni-app x 蒸汽模式!
uni-app
源码手记1 天前
基于微信小程序的美甲美睫预约系统-毕设源码
微信小程序·小程序·课程设计
anyup1 天前
uni-app x 的 Signature 签名板与练字格,一个组件多端支持 App/鸿蒙/H5/小程序
前端·vue.js·uni-app
微订校园外卖系统1 天前
自营小程序低成本落地:交付链路建模与首单联调清单
小程序·外卖系统·本地生活·微订
微订外卖系统2 天前
门店小程序从零上线:单店实体建模与订单状态机梳理
小程序·外卖系统·本地生活·微订
西泽XIZ93 天前
微信小程序网络与数据库交互实践:从后端环境搭建到数据渲染
网络·数据库·微信小程序·小程序
知了学历孙老师3 天前
考研报名档案所在地填错,调档和录取会出什么岔子
考研·小程序
夜-未央3 天前
微信小程序多端插件获取OAID实践
微信小程序·小程序
AI源码3 天前
体育场馆预约小程序
小程序
普通人63 天前
uniapp鸿蒙开发完整指南
华为·uni-app·harmonyos