vue3+ts 日期转年龄(utils工具类)
【代码】vue3+ts 日期转年龄(utils工具类)
·
/**
* 生日日期转年龄
* @param {string} birth 2024-07-02
* @returns {number}
*/
export const calculateAge = (birth: string) => {
const birthday = new Date(birth);
const today = new Date();
const ageInMilliseconds = today.getTime() - birthday.getTime();
const ageInYears = Math.floor(
ageInMilliseconds / (365 * 24 * 60 * 60 * 1000)
);
return ageInYears;
};
import {calculateAge } from "/@/utils/utils";//引入
//页面使用(后端返回的是2024-07-02 00:00:00所以需要使用.substring(0, 10)方法截取,只返回日期则直接使用返回的变量)
<el-table-column align="center" label="年龄(岁)" width="110">
<template #default="scope">
{{
scope.row.birthday
? calculateAge(scope.row.birthday.substring(0, 10))
: "-"
}}
</template>
</el-table-column>
更多推荐
已为社区贡献18条内容
所有评论(0)