首先写出一个日历我们需要考虑以下2个问题:

  • 每个月的总天数
  • 每个月的第一天周几

这里提供了一个判断平年闰年2月份天数的方法:

function leapYear(year) {
return (year%100==0?res=(year%400==0?1:0):res=(year%4==0?1:0));
}

1.因此可以得到12个月份天数的数组:

const monthDays = new Array(31, 28 + leapYear(year), 31, 30, 31, 31, 30, 31, 30, 31, 30, 31)

因为获取到的月份是0-11,所有刚好和数组的下标对应上。

2.获取每个月的1日是星期几:

let monthDayOne = new Date(2019, 12, 1)
const firstday = monthDayOne .getDay()

通过月总天数和该月第一天是星期几两个条件就可以得到行数,解决表格所需行数问题:(当前月天数+第一天是星期几的数值)/ 7

const date = new Date()
const mnow = date.getMonth()
const tr_str = Math.ceil((monthDays[mnow] + firstday)/7);

其次就是渲染问题了

完整的js代码如下:

const date = new Date()
const {year, month, day} = {
year: date.getFullYear(),
month: date.getMonth(),
day: date.getDate()
}
let monthDayOne = new Date(year, month, 1)
const firstday = monthDayOne.getDay() const monthDays = new Array(31, 28 + leapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
const tr_str = Math.ceil((monthDays[month] + firstday) / 7) function leapYear(year) {
return (year%100==0?res=(year%400==0?1:0):res=(year%4==0?1:0));
}

这是我写的一个简单的渲染:

//打印表格第一行(有星期标志)
document.write ("<table border='1' align='center' width='220' cellspacing='0'><tr><td align='center'>日</td><td align='center'>一</td><td align='center'>二</td><td align='center'>三</td><td align='center'>四</td><td align='center'>五</td><td align='center'>六</td></tr>");
for(i=0;i<tr_str;i++) { //表格的行
document.write("<tr>");
for(k=0;k<7;k++) { //表格每行的单元格
idx=i*7+k; //单元格自然序列号
date_str=idx-firstday+1; //计算日期
(date_str<=0 || date_str>m_days[mnow]) ? date_str=" " : date_str=idx-firstday+1; //过滤无效日期(小于等于零的、大于月总天数的)
//打印日期:今天底色为红
date_str==dnow ? document.write ("<td align='center' bgcolor='red'>" + date_str + "</td>") : document.write ("<td align='center'>" + date_str + "</td>");
}
document.write("</tr>"); //表格的行结束
} document.write("</table>"); //表格结束

  效果如下:

 

 

最新文章

  1. AngularJS 系列 学习笔记 目录篇
  2. 在 Arch Linux 玩百度 Flash 战曲游戏乱码
  3. linux 压缩命令详解
  4. c++ 常数后缀说明
  5. 数据库的点数据根据行政区shp来进行行政区处理,python定时器实现
  6. HW—可怕的阶乘n!__注意大数据函数的使用BigInteger
  7. POJ 2686 Traveling by Stagecoach 壮压DP
  8. 哞哞快的 C# 高斯模糊实现
  9. 【转】C/CPP之static
  10. Linux 常用命令之二
  11. 分享如何将git项目导入GitHub(附创建分支)
  12. IDC服务器的六大基础知识
  13. Ubuntu 17.10 UTC
  14. 快速构建SPA框架SalutJS--项目工程目录 一
  15. IP通信基础学习第三周(下)
  16. sizeof 4字节对齐
  17. 100道Java基础面试题
  18. grafana 邮件报警
  19. FineReport——函数
  20. (转) HA的几种方案

热门文章

  1. .lib和.dll文件
  2. jmeter 参数化大数据取唯一值方式
  3. 详解CI、CD相关概念
  4. 【maven】插件和依赖管理
  5. js页面 :函数名 is not defined
  6. 运维笔记--linux环境提示python: command not found
  7. 修改 commit 历史
  8. [Design Patterns] 02. Structural Patterns - Facade Pattern
  9. 【LeetCode算法-21】Merge Two Sorted Lists
  10. [LeetCode] 712. Minimum ASCII Delete Sum for Two Strings 两个字符串的最小ASCII删除和