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}天`
};
相关推荐
Highcharts.js4 小时前
成分占比饼图代码|常用可视化图表开发示例
java·开发语言·仪表盘·highcharts·实战代码·响应式图表
蓝博AI5 小时前
2027基于yolov8飞机蒙皮缺陷检测,支持图像,视频和摄像实时检测,python源码
开发语言·python·yolo
@atweiwei6 小时前
LangChainRust 0.33.0 发布:让 Agent 应用更容易运行、观察和评测
服务器·前端·javascript
郝学胜-神的一滴8 小时前
游戏设计、原型与开发 26:四种循环
开发语言·数据结构·游戏·游戏引擎·游戏策划
泡海椒9 小时前
Java PDF 报表开发:一页简历的两种版式风格对比与折行避坑
java·开发语言·pdf
2601_962885729 小时前
如何用 Python 计算终极振荡器(Ultimate Oscillator, UOS)?
开发语言·python
benchmark_cc10 小时前
一次获取多只股票实时行情:QuantDash `quotes.get(symbols=[...])` 批量快照
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
geovindu10 小时前
python: PCA
开发语言·后端·python·算法
__万波__11 小时前
嵌入式存储技术--1.Flash物理存储
java·开发语言
Chen_harmony11 小时前
十六、ALV树
开发语言·c++