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

完成~

相关推荐
军军君0110 小时前
基于Springboot+UniApp+Ai实现模拟面试小工具四:后端项目基础框架搭建下
spring boot·spring·面试·elementui·typescript·uni-app·mybatis
Byte_Me12 小时前
IoT 小程序:如何破解设备互联的碎片化困局?
物联网·小程序·iot
小徐_233314 小时前
uni-app 弹窗总被父元素“绑架”?3招破局,H5/小程序/APP一招通杀!
前端·微信小程序·uni-app
Java陈序员20 小时前
又一款基于 SpringBoot + Vue 实现的开源新零售商城系统!
vue.js·spring boot·uni-app
2501_915921431 天前
没有Mac如何完成iOS 上架:iOS App 上架App Store流程
android·ios·小程序·https·uni-app·iphone·webview
说私域1 天前
基于定制开发开源AI智能名片与S2B2C商城小程序的旅游日志创新应用研究
人工智能·小程序·旅游
脑袋大大的1 天前
钉钉小程序开发环境配置与前端开发指南
小程序·钉钉·企业应用开发
玩代码的菜鸟1 天前
uniapp类似抖音视频滑动
uni-app
2301_805962932 天前
微信小程序控制空调之接收MQTT消息
微信小程序·小程序·esp32
The_era_achievs_hero2 天前
微信小程序121~130
微信小程序·小程序