JS+TS+Dayjs实现出生日期到当前日期是*岁*月*天

备注:

本例子中有两个参数 一个是出生日期另外一个是当前日期格式都是"1995-06-24"这种格式,能够精确算出月*天,具体实现代码如下

javascript 复制代码
/**
 * 
 * @param birthDay 出生日期
 * @param curDate 当前日期
 * @returns 
 */
export const birthToAgeDiff = (birthDay: string, curDate: string) => {
  const birth = dayjs(birthDay);
  const now = dayjs(curDate);
  if(birth.valueOf()> now.valueOf()) return '未出生~'

  let years = now.year() - birth.year();
  let months = now.month() - birth.month();
  let days = now.date() - birth.date();

  if (days < 0) {
    months -= 1;
    days += dayjs(now).subtract(1, 'month').daysInMonth();
  }

  if (months < 0) {
    years -= 1;
    months += 12;
  }
  return ` ${years}岁${months}月${days}天`
};
相关推荐
geats人山人海8 小时前
c# 第九章 record
开发语言·c#
早期的虫儿有鸟吃8 小时前
vue2--Vuex 模块化
开发语言·前端·javascript
浪客川8 小时前
Android的SystemUI的启动流程简析
android·开发语言
Cobyte8 小时前
使用 JavaScript 实现有限状态机的经典问题
前端·javascript·vue.js
-银雾鸢尾-8 小时前
C#中的抽象类与抽象方法
开发语言·c#
acheding9 小时前
File System Access API 实战:让网页真正读写本地文件
前端·javascript·vue.js·编辑器·markdown
何时梦醒9 小时前
⚛️ React 19 + TypeScript 深度学习笔记 —— 从组件化思维到 WebGPU 端侧 AI 落地
前端·javascript·人工智能
萧瑟余晖9 小时前
JDK 20 新特性详解
java·开发语言
benchmark_cc9 小时前
如何用 Python 进行多周期 K 线合成与时区对齐?基于 QuantDash 与 Pandas 的量化数据清洗实战(附 GitHub 源码)
开发语言·python·github·盯盘·pandas·quantdash·量化数据
用户938515635079 小时前
从 Vite 脚手架到 WebGPU 推理:手写一个 DeepSeek-R1 浏览器端大模型 Demo
javascript·人工智能·全栈