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 小时前
无法访问org.springframeword.beans.factory.annotation.Value
java·开发语言·spring boot
S-码农1 小时前
Linux ——条件变量
linux·开发语言
清水白石0081 小时前
《Python 编程全景解析:从核心精要到 Hypothesis 属性基测试的边界探索》
开发语言·python
IT枫斗者1 小时前
IntelliJ IDEA 2025.3史诗级更新:统一发行版+Spring Boot 4支持,这更新太香了!
java·开发语言·前端·javascript·spring boot·后端·intellij-idea
NGC_66112 小时前
二分查找算法
java·javascript·算法
勇往直前plus2 小时前
深入理解 Python 内存模型:模块、类、对象的存储与运行机制
开发语言·python
派大星-?2 小时前
自动化测试五模块一框架(下)
开发语言·python
享誉霸王2 小时前
15、告别混乱!Vue3复杂项目的规范搭建与基础库封装实战
前端·javascript·vue.js·前端框架·json·firefox·html5
三无少女指南3 小时前
开发者环境配置:用 Ollama 实现本地大模型部署(附下载慢的解决方案
c语言·开发语言·数据库·ubuntu