Date 的工具函数

/**
 * 获取当天零点零时零分零秒的日期对象
 *
 * @return {Date}
 */
const getToDayStart = () => {
  const date = new Date();
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);
  date.setMilliseconds(0);
  return date;
};

/**
 * 获取当天最后一秒的日期对象
 *
 * @return {Date}
 */
const getToDayEnd = () => {
  const date = new Date();
  date.setHours(23);
  date.setMinutes(59);
  date.setSeconds(59);
  date.setMilliseconds(999);
  return date;
};

/**
 * 判断一个日期是否为闰年
 *
 * @param {Date} date
 * @return {Boolean}
 */
const isLeapYear = (date) => {
  const year = date.getFullYear();
  return year % 4 === 0;
};

/**
 * 获取本周的一天
 *
 * @param {Number} day 0 ~ 6 代表 周日到周六
 * @param {Date?} date 计算的日期对象, 默认为当天
 * @return {Date}
 */
const getDayInThisWeek = (day, date) => {
  if (typeof day !== 'number') throw new Error('参数只支持 number 类型');
  if (day < 0 || day > 6) throw new Error('参数只支持 0 ~ 6 的数字');
  if (typeof day !== 'number') throw new Error('参数只支持 number 类型');
  date = date || getToDayStart();
  const currentWeek = date.getDay();
  const currentDay = date.getDate();
  date.setDate(currentDay + (day - currentWeek));
  return date;
};
/**
 * 获取当月的天数
 *
 * @param {Date?} date 计算的日期对象, 默认为当天
 * @return {Number}
 */
const getMonthDayCount = (date) => {
  date = date || getToDayStart();
  const mouth = date.getMonth() + 1;
  if (mouth === 2) return isLeapYear(date) ? 29 : 28;
  if ([4, 6, 9, 11].includes(mouth)) return 30;
  return 31;
};
/**
 * 获取当月最后一天的日期对象
 *
 * @param {Date?} _date 计算的日期对象, 默认为当天
 * @return {Date}
 */
const getLastDayInThisMount = (_date) => {
  const date = new Date(_date || getToDayStart());
  date.setDate(getMonthDayCount(date));
  return date;
};
/**
 * 获取日期在当月的第几周
 *
 * @param {Date?} _date 计算日期, 默认为今天
 * @return {Number}
 */
const getWhichWeekInThisMount = (_date) => {
  const date = new Date(_date || new Date());
  const firstDate = new Date(date);
  firstDate.setDate(1);
  return Math.ceil((date.getDate() - firstDate.getDate() + firstDate.getDay()) / 7);
};
/**
 * 获取当月周数(包括不完整周)
 *
 * @param {Date?} _date 计算日期, 默认当前日期
 * @return {Number}
 */
const getThisMountWeekCount = (_date) => {
  const date = new Date(_date || new Date());
  const firstDate = new Date(date);
  firstDate.setDate(1);
  const lastDate = getLastDayInThisMount(_date);
  return (lastDate.getDate() - firstDate.getDate() + 1 + firstDate.getDay() + (6 - lastDate.getDay())) / 7;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

eno_zeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值