DIV CSS 佈局教程網

用 JS 打造日曆:計算指定日期的周數與星期
編輯:JavaScript綜合知識     

本文示範如何撰寫一個簡易日曆:在使用者輸入日期後,程式能算出這一天是該年的第幾天、屬於第幾週,並判斷是星期幾。因為需要互動,於是選用 JavaScript 實作,也算是结对編程的一次有趣嘗試。

取值與呼叫

畫面以 HTML 呈現,點擊按鈕觸發 onCheck(),先取得年、月、日的輸入值,轉型後呼叫核心函式 days():

function onCheck(){
  var Year = document.getElementById("year").value;
  var theYear = Year * 1;
  var month = document.getElementById("month");
  var theMonth = month.options[month.selectedIndex].value;
  var day = document.getElementById("day");
  var theDay = day.options[day.selectedIndex].value;
  // 輸入值判斷...
  days(theYear, theMonth, theDay);
}

核心計算函式

days() 先累加各月天數,再加上當月的日數,最後換算出是當年第幾天、第幾週與星期幾:

function days(year, month, day) {
  var days = 0;
  for(var i = 1; i < month; i++){
    switch(i){
      case 1: case 3: case 5: case 7: case 8: case 10: case 12:
        days += 31; break;
      case 4: case 6: case 9: case 11:
        days += 30; break;
      case 2:
        days += isLeapYear(year) ? 29 : 28; break;
    }
  }
  days += day * 1;
  var date0 = new Date(year, 0, 1);
  var date1 = new Date(year, month-1, day);
  var nthOfWeek = Math.floor((days + date0.getDay() + 6) / 7);
  var toDay = new Array("星期天","星期一","星期二","星期三","星期四","星期五","星期六");
  alert("該日期是一年中的第"+days+"天\n"+"是第"+nthOfWeek+"周的"+toDay[date1.getDay()]);
}

輸入驗證

在實際操作資料前,務必先驗證輸入是否合法,避免閏年二月、小月 31 日等錯誤:

if (isNaN(theYear) || theYear < 0) { alert("輸入有誤,請重新輸入"); return; }
if((theMonth==2 && theDay>29 && isLeapYear(theYear)) || (theMonth==2 && theDay>28 && !isLeapYear(theYear))) { alert("輸入有誤,請重新輸入"); return; }
if((theMonth==4||theMonth==6||theMonth==9||theMonth==11) && theDay==31) { alert("輸入有誤,請重新輸入"); return; }

除錯過程中最常遇到的就是型別不匹配導致的計算錯誤與數值捨入問題。透過清楚的分工——一人負責審核抓蟲、一人負責編碼實作——再搭配完善的輸入測試,就能快速完成並健全功能。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved