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

完成~

相关推荐
天***88968 小时前
小程序婚纱店摄影楼预约婚庆礼展示,小程序开发定制,会员下单档期系统
小程序
说私域8 小时前
开源AI智能名片链动2+1模式商城小程序下短视频电商变现与广告变现的对比研究
人工智能·小程序
homelook9 小时前
uniapp蓝牙demo
uni-app
天***889611 小时前
美业医疗美容院小程序,预约会员管理养生馆诊所肌护肤理疗系统,附源码交付
小程序
2501_915909061 天前
手机崩溃日志导出的工程化体系,从系统级诊断到应用行为分析的多工具协同方法
android·ios·智能手机·小程序·uni-app·iphone·webview
toooooop81 天前
微信小程序轮播图高度自适应优化
微信小程序·小程序
郑州光合科技余经理1 天前
技术视角:海外版一站式同城生活服务平台源码解析
java·开发语言·uni-app·php·排序算法·objective-c·生活
StarChainTech1 天前
电动车租赁行业的核心需求:智能中控设备的选择与技术方案
物联网·微信小程序·小程序·软件需求·共享经济
计算机毕设指导61 天前
基于微信小程序的积分制零食自选平台【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
云起SAAS1 天前
老年美文文章图文短视频资讯阅读抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·老年美文文章图文短视频资讯阅读