代碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <div style="background-color:yellow;"> <span> <script type="text/javascript"> var date = new Date(); document.write("今天是:" + date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日" + " 星期" + "日一二三四五六".charAt(date.getDay())); </script> </span> </div> </body> </html>
結果顯示為
var date = new Date(); 聲明一個名稱為date的對象,賦值為new Date(); new Date();表示創建了一個日期對象,返回值為當前日期。
document.write(); 向輸出流(文檔)寫入文本或HTML。
date.getFullYear() 從Date對象以四位數字返回年份
date.getMonth()+1 從Date對象返回月份(0-11),返回當前月份需+1。
date.getDate() 從Date對象返回一個月中的某一天(1-31)。
stringObject.charAt(index) 方法可返回指定位置的字符。index表示字符串中某個位置的數字,即字符在字符串中的下標
date.getDay() 從 Date 對象返回一周中的某一天 (0 ~ 6)。0為星期日。
"日一二三四五六".charAt(date.getDay()) 就是date.getDay()返回0~6數字,同時代表"日一二三四五六"字符串的下標。