学习地址:

一、项目搭建

  1. npm init -y
  2. yarn add vite sass -D
  3. 新建结构目录

image.png

  1. npm run dev 运行项目

    二、项目分析

    image.png

  2. 第一行为星期

  3. 需要知道上个月渲染多少个 -> 知道当月1号星期几
  4. 需要知道下个月渲染多少个 -> 6 * 7 - 上个月渲染多少天 - 当月多少天
  5. 需知道上个月最后一天是几号
  6. 需要知道本月一共多少天
  7. 今天显示
  8. 点击日期输出 -> yy-mm-dd

三、工具函数准备

  1. 本月1号为星期几

    1. function getFirstWeekDay(year, month) { // 注意:0(1月)- 11(12月)
    2. const date = new Date(year, month - 1, 1);
    3. return date.getDay();
    4. }
  2. 当月多少天 -> 当月最后一天

    1. function getMonthDayCount(year, month) {
    2. const date = new Date(year, month, 0); // 获取下一个月的前一天
    3. return date.getDate();
    4. }
  3. 获取上个月渲染天数

    1. function getLastMonthRestDays(year, month) {
    2. const days = getFirstWeekDay(year, month);
    3. let lastDate = getMonthDayCount(year, month - 1);
    4. const restDays = [];
    5. while (restDays.length < days) {
    6. restDays.push(lastDate--);
    7. }
    8. return restDays.reverse();
    9. }
  4. 获取下个月渲染天数

    1. function getNextMonthRestDays(year, month) {
    2. const lastMonthRestDayCount = getFirstWeekDay(year, month);
    3. const currentMonthDayCount = getMonthDayCount(year, month);
    4. const nextMonthRestDayCount =
    5. 42 - lastMonthRestDayCount - currentMonthDayCount;
    6. let restDays = [];
    7. for (let i = 1; i < nextMonthRestDayCount; i++) {
    8. restDays.push(i);
    9. }
    10. return restDays;
    11. }
  5. 时间戳转换

    1. function getDateInfo(tiemStemp) {
    2. var date = tiemStemp ? new Date(tiemStemp) : new Date();
    3. return [
    4. date.getFullYear(),
    5. date.getMonth() + 1,
    6. date.getDate()
    7. ]
    8. }
  6. 日期格式化

    1. function getFormatDate(year, month, date) {
    2. const dateArr = [year, month, date];
    3. for (let i = 0; i < dateArr.length; i++) {
    4. dateArr[i] < 10 && (dateArr[i] = "0" + dateArr[i]);
    5. }
    6. return dateArr.join("-");
    7. }