前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >年月日借位相减,输入两个时间点的 年月日

年月日借位相减,输入两个时间点的 年月日

作者头像
拿我格子衫来
发布2022-01-24 11:25:01
1.3K0
发布2022-01-24 11:25:01
举报
文章被收录于专栏:TopFETopFE
代码语言:javascript
复制
/**
 * 计算两个日期的时长,返回x年x月x日,传入时间戳
 */
export function getDateDurations (startDate, endDate) {
  let startYear = parseInt(moment(startDate).format('YYYY'))
  let startMonth = parseInt(moment(startDate).format('MM'))
  let startDay = parseInt(moment(startDate).format('DD'))
  let endYear = parseInt(moment(endDate).format('YYYY'))
  let endMonth = parseInt(moment(endDate).format('MM'))
  let endDay = parseInt(moment(endDate).format('DD')) + 1
  let currentMonthDays = 31
  if ([1,3,4,7,8,10,12].includes(startMonth)) {
    currentMonthDays = 31
  } else if ([4,6,9,11].includes(startMonth)) {
    currentMonthDays = 30
  } else if (startMonth === 2) {
    currentMonthDays = 28
  }

  let monthJ1 = false // 是否需要向上级月份借位
  let yearJ1 = false // 是否需要向上级年份借位
  let mDay = endDay - startDay
  let mMonth = endMonth - startMonth
  let mYear = endYear - startYear

  if (mDay < 0) {
    monthJ1 = true
    mDay = mDay + currentMonthDays
  }

  if (monthJ1) {
    mMonth = mMonth - 1
  }
  if (mMonth < 0) {
    yearJ1 = true
    mMonth = mMonth + 12
  }
  if (mYear > 0) {
    if (yearJ1) {
      mYear = mYear - 1
    }
  }
  return (mYear ? mYear + '年' : '') + (mMonth ? mMonth + '月' : '') + (mDay ? mDay + '日' : '')
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档