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}天`
};
相关推荐
AKA__Zas3 分钟前
初识多线程(初初识)
java·服务器·开发语言·学习方法
zhangrelay7 分钟前
三分钟云课实践速通--概率统计--python版
linux·开发语言·笔记·python·学习·ubuntu
张赐荣13 分钟前
深入详解在 Python 中用 ctypes 调用 Windows API 清空回收站
开发语言·windows·python
费曼学习法15 分钟前
快速选择算法:如何在 10 亿数据中瞬间找到“第 K 大”?
javascript·算法
用户9623779544817 分钟前
原理分析 | Controller —— SpringBoot 内存马
javascript·后端
彷徨而立17 分钟前
【C/C++】在头文件中定义全局变量的方法
c语言·开发语言·c++
写代码的皮筏艇30 分钟前
replace方法
前端·javascript
我命由我1234532 分钟前
Android 广播 - 显式广播与隐式广播
android·java·开发语言·java-ee·kotlin·android studio·android-studio
不知名的老吴32 分钟前
聊一聊年轻的编程语言Golang与Rust
开发语言·golang·rust