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

完成~

相关推荐
上海秉坤20 小时前
小程序如何打通门店?预约、券码核销与会员服务记录的流程设计
小程序·零售
派小心.2 天前
网站统计采样数据的误差核对
大数据·服务器·前端·数据库·人工智能·小程序·数据分析
河北清兮网络科技2 天前
广告联盟 APP 介绍:搭建属于自己的流量变现平台
小程序·app·产品经理·短剧app·广告联盟
微擎应用市场2 天前
多功能预约公众号管理系统介绍
微信小程序·小程序
JQweryuiop2 天前
SaaS商城软件与定制开发该怎么选?推荐七彩屋商城小程序系统
小程序
青企通2 天前
传统企业数字化转型的技术路径:从需求建模到小程序 MVP 的落地方法
小程序·php·apache
andrsted2 天前
练题簿助学教学:在线刷题、随堂考试,让一门课拥有自己的题库
学习·微信小程序·小程序·学习方法·刷题
派小心.2 天前
网站统计多域名数据隔离配置
大数据·数据库·人工智能·小程序·数据分析
2501_915921432 天前
iOS应用从开发到上架App Store的完整步骤详解
android·ios·小程序·https·uni-app·iphone·webview
省钱兄--zs2 天前
深圳24小时自助健身房软硬件解决方案实战指南与开发流程详解
java·数据仓库·spring boot·小程序·架构