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}天`
};
相关推荐
FuckPatience1 天前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
林恒smileZAZ1 天前
Vue<前端页面版本检测>
前端·javascript·vue.js
014-code1 天前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly2024061 天前
组合模式(Composite Pattern)
开发语言
我是Superman丶1 天前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
游乐码1 天前
c#泛型约束
开发语言·c#
Dontla1 天前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen1 天前
python rest请求、requests
开发语言·python
Huanzhi_Lin1 天前
关于V8/MajorGC/MinorGC——性能优化
javascript·性能优化·ts·js·v8·新生代·老生代
铁东博客1 天前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang