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}天`
};
相关推荐
xxie12379444 分钟前
return与print
开发语言·python
秋91 小时前
从 Python 后端工程师转型 AI Engineer(AI 工程化)的完整补课清单(2026实战版)
开发语言·人工智能·python
程序员二叉1 小时前
【Java】 异常高频面试题精讲 | 易错点+对比总结
java·开发语言·面试
慕木沐2 小时前
Google ADK Java 1.0版本 核心机制与实战 Demo
java·开发语言·python
Roann_seo%2 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++
huangdong_3 小时前
淘宝商品SKU图自动分类技术深度解析:从DOM解析到智能归档
开发语言·javascript·ecmascript
阿正的梦工坊3 小时前
【Rust】12-借用检查器与非词法生命周期
开发语言·后端·rust
qq_2518364573 小时前
基于java Web网络订餐系统设计与实现 源码文档
java·开发语言·前端
秋93 小时前
3年经验Python后端转AI Engineer:3个月实战转型计划(2026版)
开发语言·人工智能·python
凡人叶枫3 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法