最近在搗鼓一個chrome插件,包括兩個功能:1.倒計時虾标,2.日歷寓盗。
大致是下面這個樣子:
倒計時模式倒還簡單灌砖,日歷剛開始以為困難點璧函,仔細分析后也還挺順利。
寫過日歷的一般都知道有四點很重要:
1.一個月中有幾天
2.一個月中第一天星期幾
3.一個月中第后一天星期幾
4.正確的處理換行
從我寫這個日歷的思路開始:
1.剛開始思路有點亂基显,想著既要輸出月份蘸吓,又要輸出月中的天數(shù),還要處理各種換行撩幽,好多事库继。后來我就想倒退吧,先輸出一個月的窜醉,如果指定月份的日歷輸出了宪萄,下面就是循環(huán)遍歷月份就行了。
下面是三月份的日歷輸出代碼:
let today = new Date(),
year = today.getFullYear(),
month = today.getMonth();
// ?
let dayStr = '';
// 3月有31天
let dayInMonth = 31;
// 每個月的第一天
let firstDay = new Date(year,month,1);
// 每個月的最后一天
let lastDay = new Date(year,month,31);
//第一天星期幾(0-6)
let weekday = firstDay.getDay();
// 當(dāng)月的最后一天星期幾
let lastDayWeekDay = lastDay.getDay();
// 每一個都是從1號開始
let date = 1;
// ?
// 補齊前面的空格
for(let i = 0; i < weekday; i++){
dayStr += '+ ';
}
for(;date <= dayInMonth;date++){
dayStr += date + ' ';
weekday++
// 換行處理
if(weekday%7 == 0){
weekday = 0;
dayStr += '\n';
}
}
// 補齊后面的空格
for(let j = 0; j < (7 - lastDayWeekDay - 1); j++){
dayStr += '+ ';
}
可以把上面代碼拷貝到控制臺執(zhí)行榨惰,看下效果拜英。
可能看上去還不像日歷,日歷是有頭的琅催,周幾居凶,周幾虫给,把下面代碼分別加入上面代碼?處。
let weeks = ['日','一','二','三','四','五','六'];
dayStr += weeks.join(' ') + '\n';
這樣就比較像了侠碧。其實講到這里基本日歷就差不多了抹估,還有一個重要的方法,就是算出指定月份的天數(shù)弄兜,其實JS的 Date 里沒有給出api药蜻,所以需要自己算。
好憂傷挨队,我查了一下python里的日歷相關(guān)的給了方法谷暮。但是JS里有一個 getDate() 方法獲取月份中的第幾天。經(jīng)過網(wǎng)上的搜索盛垦,得到如下方法:
function daysInMonth(month, year) {
return new Date(year, month + 1, 0).getDate();
}
我來解釋一下:當(dāng)我們嘗試傳入0(月份是 0-11 )一月份湿弦,2017,得到 new Date(2017,1,0)腾夯。這代表是2月份的第0天颊埃,好奇怪,哪有第0天的蝶俱?其實某月的第0天就是前一個月的最后一天班利,所以就得到了某月的天數(shù)。
完整代碼如下:
function daysInMonth(month, year) {
return new Date(year, month + 1, 0).getDate();
}
let weeks = ['日','一','二','三','四','五','六'];
let year = new Date().getFullYear();
let dayStr = '';
for(let month = 0; month <=11; month++){
// 每個月的第一天
let firstDay = new Date(year,month,1);
let dayInMonth = daysInMonth(month,year);
// 每個月的最后一天
let lastDay = new Date(year,month,dayInMonth);
// 第一天星期幾(0-6)
let weekday = firstDay.getDay();
// 最后一天星期幾
let lastDayWeekDay = lastDay.getDay();
// 每一個都是從1號開始
let date = 1;
dayStr += weeks.join(' ') + '\n';
// 補齊前面的空格
for(let i = 0; i < weekday; i++){
dayStr += '+ ';
}
for(;date <= dayInMonth;date++){
dayStr += date + ' ';
weekday++
if(weekday%7 == 0){
weekday = 0;
dayStr += '\n';
}
}
// 補齊后面的空格
for(let j = 0; j < (7 - lastDayWeekDay - 1); j++){
dayStr += '+ ';
}
dayStr += '\n\n';
}
更新:
添加githunb地址:https://github.com/ghostcode/countdown
參考:
1.http://stackoverflow.com/questions/315760/what-is-the-best-way-to-determine-the-number-of-days-in-a-month-with-javascript
2.https://github.com/lishengzxc/bblog/issues/5