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

完成~

相关推荐
小徐_23332 天前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
宸翰3 天前
解决 uni-app App 端 vue-i18n 占位符丢失:封装跨端可用的 tf 格式化方法
前端·vue.js·uni-app
时光足迹4 天前
uni-app 视频通话实战:康复师与患者视频问诊的 6 个致命 Bug 与解决方案
android·ios·uni-app
时光足迹4 天前
腾讯云 TRTC UniApp SDK 从入门到上线
前端·vue.js·uni-app
时光足迹4 天前
uni-app 里把加密视频嵌入页面播放?我分析了 4 种方案,只有 1 种接近完美
前端·vue.js·uni-app
时光足迹4 天前
JPush UniApp UTS 插件完全参考手册:API、事件与厂商通道一网打尽
vue.js·ios·uni-app
时光足迹4 天前
极光推送全攻略(下):uni-app 代码实现与 iOS 排查实战
vue.js·ios·uni-app
时光足迹4 天前
极光推送全攻略(上):被iOS证书折磨了三天,我写了一份前端也能看懂的避坑指南
前端·ios·uni-app
spmcor6 天前
身份证读卡“无感登录”方案实践:从手动点击到自动检测
uni-app
PedroQue996 天前
uni-router v1.8.0新增冷启动守卫补执行
前端·uni-app