日历日期calendar.js

日历js

const calendar: any = {};

let today = new Date();

calendar.getMonthDate = function (
  year = today.getFullYear(),
  month = today.getMonth() + 1
) {
  // 这个月第一天的Date对象
  const firstDay = new Date(year, month - 1, 1);
  // 那个这个月第一天具体是星期几
  let firstDayWeekDay = firstDay.getDay();
  // 0的话就是星期天
  if (firstDayWeekDay === 0) firstDayWeekDay = 7;
  // 拿到当前的年份
  year = firstDay.getFullYear();
  // 拿到当前的月份
  month = firstDay.getMonth() + 1;
  // 上个月的最后一天
  const lastDayofLastMonth = new Date(year, month - 1, 0);
  // 上个月的具体日期
  const lastDateofLastMonth = lastDayofLastMonth.getDate();
  // 上个月在第一行要显示几天
  const preMonthDayCount = firstDayWeekDay;
  // 这个月的最后一天
  const lastDay = new Date(year, month, 0);
  // 这个月的最后一天具体日期
  const lastData = lastDay.getDate();
  const ret: any[] = [];

  for (let i = 0; i < 6 * 7; i++) {
    // 赋值date的值,这里上个月的最后一天为0
    const date = i + 1 - preMonthDayCount;
    // 赋值showDate,上下月份,下面再做判断
    let showDate = date;

    // 赋值月份
    let thisMonth = month;

    // 当date < 0时,则代表是上一个月
    if (date <= 0) {
      thisMonth = month - 1; // 月份减一
      showDate = lastDateofLastMonth + date; // 显示上一个相应是几号
    } else if (date > lastData) {
      // 当date大于了这个月最后一天,那么代表下个月
      thisMonth = month + 1; // 月份加一
      showDate = showDate - lastData; // 显示下一个月具体几号
    }

    // 当我们月份是13的时候,代表下一年,月份置为一
    if (thisMonth === 13) thisMonth = 1;

    // 当我们月份是0的时候,代表上一年,月份置为一
    if (thisMonth === 0) thisMonth = 12;

    ret.push({
      date: new Date(year, thisMonth - 1, showDate),
      data: `${year}-${String(thisMonth).padStart(2, "0")}-${String(
        showDate
      ).padStart(2, "0")}`
    });
  }

  return {
    days: ret,
    today: today
  };
};

calendar.preMonth = function () {
  let thisMonth = today.getMonth();
  let thisYear = today.getFullYear();
  thisMonth--;
  if (thisMonth === 0) {
    thisMonth = 12;
    thisYear--;
  }
  today = new Date(thisYear, thisMonth, 1);
  return this.getMonthDate();
};

calendar.today = function () {
  today = new Date();
  return this.getMonthDate();
};

calendar.nextMonth = function () {
  let thisMonth = today.getMonth();
  let thisYear = today.getFullYear();
  thisMonth++;
  if (thisMonth === 13) {
    thisMonth = 1;
    thisYear++;
  }
  today = new Date(thisYear, thisMonth, 1);
  return this.getMonthDate();
};

calendar.format = (format: string, date: any) => {
  const obj = {
    yyyy年MM月: () =>
      `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, "0")}`
  };
  return obj[format] && obj[format]();
};

export default calendar;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值