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}天`
};
相关推荐
爱写代码的小朋友1 小时前
从零开始学 Win32 API:C++ 窗口编程实战(VS Code + MinGW-w64 命令行详解)
开发语言·c++
果汁华1 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
小小晓.1 小时前
C++:语句和作用域
开发语言·c++
wanderist.2 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
kyriewen3 小时前
我review了一份Vibe Coding写的前端代码——能跑,但5个地方迟早要命
前端·javascript·ai编程
海天鹰3 小时前
PHP上传文件
android·开发语言·php
Yeauty5 小时前
渲染成图再 CLI 拼接,还是进程内直推?Rust 帧到视频的两条路
开发语言·rust·音视频
Hilaku5 小时前
为什么在 2026 年,MPA(多页面应用)正在悄悄复辟?
前端·javascript·程序员
geovindu5 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
悟空瞎说5 小时前
iOS 高效绘图
javascript