DIV CSS 佈局教程網

用 JavaScript 自動顯示當天日期,並轉成中文數字
編輯:JavaScript綜合知識     

頁首或頁尾那行「今天是 X 月 X 日」,如果靠手打,過一天就過期。交給 Date 物件處理,頁面永遠顯示正確日期。

取得日期的三個方法

getMonth() 回傳的是 0 到 11,所以必須加一才是人類認得的月份;getDate() 拿到當月幾號;getDay() 則是星期幾(0 代表週日)。這三個值組合起來就是一行完整日期。

把數字翻成中文

原範例寫了一個 number() 函式,用字串切片的方式把阿拉伯數字換成「一二三…」:

function number(index1){
  var numberstring = "一二三四五六七八九十";
  if (index1 == 0) { document.write("十") }
  if (index1 < 10) {
    document.write(numberstring.substring(0 + (index1 - 1), index1))
  } else if (index1 < 20) {
    document.write("十" + numberstring.substring(0 + (index1 - 11), (index1 - 10)))
  } else if (index1 < 30) {
    document.write("二十" + numberstring.substring(0 + (index1 - 21), (index1 - 20)))
  } else {
    document.write("三十" + numberstring.substring(0 + (index1 - 31), (index1 - 30)))
  }
}

這段寫法的問題在哪

年份被寫死成「2007年」,隔年就錯了;而且 substring 的起點運算繞了一大圈,可讀性很差。比較穩健的做法是改成回傳字串,年份則直接取 getFullYear():

var today = new Date();
var cn = "〇一二三四五六七八九";
document.write("今天是:" + today.getFullYear() + "年"
             + (today.getMonth() + 1) + "月"
             + today.getDate() + "日");

若真要中文數字,把 number() 改成 return 而非直接 document.write,就能自由拼接、也能重複使用,不必綁死在輸出動作上。

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