JS获取当天、本周、本月、本年开始时间和结束时间

本文介绍了一系列用于处理日期的实用函数,包括获取一天、一周、一月及一年的开始与结束时间的方法,适用于各种日期相关需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一天的开始时间

function startTime(time) {
  const nowTimeDate = new Date(time);
  return nowTimeDate.setHours(0, 0, 0, 0);
}

一天的结束时间

function endTime(time) {
  const nowTimeDate = new Date(time);
  return nowTimeDate.setHours(23, 59, 59, 999);
}

获取当天开始时间和结束时间

function getTodayStartTimeAndEndTime(time) {
  time = time ? time : new Date();
  return {
    startTime: new Date(time.setHours(0, 0, 0, 0)),
    endTime: new Date(time.setHours(23, 59, 59, 999)),
  };
}

获取本周开始时间和结束时间

function getCurrentWeekStartTimeAndEndTime(time) {
  const current = time ? time : new Date();
  // current是本周的第几天
  let nowDayOfWeek = current.getDay();
  if (nowDayOfWeek === 0) nowDayOfWeek = 7;
  const dayNum = 1 * 24 * 60 * 60 * 1000;
  // 获取本周星期一的时间,星期一作为一周的第一天
  const firstDate = new Date(current.valueOf() - (nowDayOfWeek - 1) * dayNum);
  // 获取本周星期天的时间,星期天作为一周的最后一天
  const lastDate = new Date(new Date(firstDate).valueOf() + 6 * dayNum);
  return {
    startTime: new Date(startTime(firstDate)),
    endTime: new Date(endTime(lastDate)),
  };
}

获取本月开始时间和结束时间

获取本月第一天
function getCurrentMonthFirst(time) {
  const date = time ? time : new Date();
  date.setDate(1);
  return startTime(date);
}
获取本月最后一天
function getCurrentMonthLast(time) {
  const date = time ? time : new Date();
  const currentMonth = date.getMonth();
  const nextMonth = currentMonth + 1;
  const nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
  const oneDay = 24 * 60 * 60 * 1000;
  return endTime(new Date(nextMonthFirstDay - oneDay));
}

获取本年开始时间和结束时间

获取本年第一天
function getCurrentYearFirst(date) {
  date = date ? date : new Date();
  date.setDate(1);
  date.setMonth(0);
  return startTime(date);
}
获取本年最后一天
function getCurrentYearLast(date) {
  date = date ? date : new Date();
  date.setFullYear(date.getFullYear() + 1); // 设置到明年
  date.setMonth(0); // 明年的0月,也就是对应到1月,是存在的哦,不是不存在的0
  date.setDate(0); // 明年的0日
  return endTime(date);
}
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值