首页前端工具函数根据类型获取对应的时间段(1-本月,2-上个月,3-近三个月,4-近一年)

根据类型获取对应的时间段(1-本月,2-上个月,3-近三个月,4-近一年)

分类前端工具函数时间2025-10-13 15:28:18发布RustStream浏览71
摘要:/** * 根据类型获取对应的时间段 * @param {number} type - 时间段类型:1-本月,2-上个月,3-近三个月,4-近一年 * @returns {Object} 包含start和end的日期对象 { start: Date, end: Date } * @throws {Error} 当type不合法时抛出错误 */ function getTimePeriod(type { const now = new Date( ; <!--autointro-->...
/**
 * 根据类型获取对应的时间段
 * @param {number} type - 时间段类型:1-本月,2-上个月,3-近三个月,4-近一年
 * @returns {Object} 包含start和end的日期对象 { start: Date, end: Date }
 * @throws {Error} 当type不合法时抛出错误
 */
function getTimePeriod(type) {
  const now = new Date();
  let start, end;

  switch (type) {
    // 1-本月
    case 1:
      start = new Date(now.getFullYear(), now.getMonth(), 1);
      end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
      break;

    // 2-上个月
    case 2:
      const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1);
      start = new Date(lastMonth.getFullYear(), lastMonth.getMonth(), 1);
      end = new Date(lastMonth.getFullYear(), lastMonth.getMonth() + 1, 0, 23, 59, 59, 999);
      break;

    // 3-近三个月
    case 3:
      const threeMonthsAgo = new Date(now);
      threeMonthsAgo.setMonth(now.getMonth() - 2); // 减2是因为从当月开始算第一个月
      start = new Date(threeMonthsAgo.getFullYear(), threeMonthsAgo.getMonth(), 1);
      end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
      break;

    // 4-近一年
    case 4:
      const oneYearAgo = new Date(now.getFullYear() - 1, now.getMonth());
      start = new Date(oneYearAgo.getFullYear(), oneYearAgo.getMonth(), 1);
      end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
      break;

    default:
      throw new Error('无效的类型,请传入1-4之间的数字(1:本月, 2:上个月, 3:近三个月, 4:近一年)');
  }

  return { startTime: moment(start).format('YYYY-MM-DD'), endTime: moment(end).format('YYYY-MM-DD') };
}

本文链接:https://blog.smallhao.fun/?id=37 转载需授权!

分享到:

Chen’Blog版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

价格转换工具函数 封装 预览组件(Vue3)

游客 回复需填写必要信息
召唤伊斯特瓦尔