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}天`
};
相关推荐
jiaguangqingpanda3 分钟前
Day36-20260204
java·开发语言
极致♀雨8 分钟前
vue2+elementUI table表格勾选行冻结/置顶
前端·javascript·vue.js·elementui
ctyshr8 分钟前
C++编译期数学计算
开发语言·c++·算法
打码的猿12 分钟前
Qt对话框不锁死主程序的方法
开发语言·qt
林shir15 分钟前
3-15-前端Web实战(Vue工程化+ElementPlus)
前端·javascript·vue.js
努力写代码的熊大26 分钟前
c++异常和智能指针
java·开发语言·c++
Yvonne爱编码31 分钟前
JAVA数据结构 DAY5-LinkedList
java·开发语言·python
千秋乐。34 分钟前
C++-string
开发语言·c++
孞㐑¥36 分钟前
算法—队列+宽搜(bfs)+堆
开发语言·c++·经验分享·笔记·算法
yufuu9844 分钟前
并行算法在STL中的应用
开发语言·c++·算法