一般的にカレンダーを自作する必要性はないと思うけど、作る必要がでてきたのでとりあえずメモ。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<!doctype html> <html lang="ja"> <head> <meta charset="utf-8" /> </head> <body> <script> let year = '2020'; let month = '1'; let html = '<table>'; html += '<tr>'; let week = ['日', '月', '火', '水', '木', '金', '土']; for (let col = 0; col < week.length; col++) { html += '<td>' + week[col] + '</td>'; } html += '</tr>'; let startWeekDay = new Date(year, month - 1, 1).getDay(); let endDay = new Date(year, month, 0).getDate(); let counter = 1; // startWeekDay: 日0, 月1, 火2, 水3, 木4, 金5, 土6 // endDay: 最終日 // counter: 書込日付 // 縦6(0~5), 横7(0~6)のループ for (let row = 0; row < 6; row++) { html += '<tr>'; for (let col = 0; col < 7; col++) { if ((row == 0 && col < startWeekDay) || (counter > endDay)) { // 第1週と最終週の判定 // 第1週: colが増えていき、startWeekDay以上の場合は日付が書き込まれる // 最終週: counterが増えていき、endDay以上になると空白 html += '<td></td>'; } else { html += '<td>' + counter + '</td>'; counter++; } } html += '</tr>'; } html += '</table>'; document.body.innerHTML = html; </script> </body> </html> |
C#(DataGridView)版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
using System; using System.Collections.Generic; using System.Windows.Forms; namespace CreateCalendar { public partial class Form1 : Form { public Form1() { InitializeComponent(); dataGridView1.AllowUserToAddRows = false; dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True; List<DataGridViewTextBoxColumn> columns = new List<DataGridViewTextBoxColumn>(); foreach(var s in new string[] { "日", "月", "火", "水", "木", "金", "土" }) { columns.Add(new DataGridViewTextBoxColumn() { HeaderText = s, Width = 120, SortMode = DataGridViewColumnSortMode.NotSortable }); } dataGridView1.Columns.AddRange(columns.ToArray()); int y = 2019; int m = 12; int startWeekDay = (int)new DateTime(y, m, 1).DayOfWeek; // 日=0, 月=1, 火=2, 水=3, 木=4, 金=5, 土=6 int endDay = new DateTime(y, m, 1).AddMonths(1).AddDays(-1).Day; int counter = 1; for (int r = 0; r < 12; r++) { dataGridView1.Rows.Add(); if (r % 2 == 0) { dataGridView1.Rows[r].Height = 18; } else { dataGridView1.Rows[r].Height = 80; } } for (int r = 0; r < 12; r = r + 2) { for (int c = 0; c < 7; c++) { if ((r == 0 && c < startWeekDay) || counter > endDay) { dataGridView1.Rows[r].Cells[c].Value = ""; } else { dataGridView1.Rows[r].Cells[c].Value = counter.ToString(); dataGridView1.Rows[r + 1].Cells[c].Value = ""; counter++; } } } } } } |