1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>获取当前日期</title> 7 <style> 8 div{ 9 background:hotpink; 10 color:lightskyblue; 11 font-family: Verdana, Geneva, Tahoma, sans-serif; 12 } 13 </style> 14 </head> 15 <body> 16 <button>显示当前时间</button> 17 <div></div> 18 <script> 19 var btn = document.querySelector(‘button‘); 20 var oDiv = document.querySelector(‘div‘); 21 btn.onclick = function(){ 22 oDiv.innerText = getDate(); 23 } 24 // 获取日期 25 function getDate(){ 26 var date = new Date(); 27 var year = date.getFullYear(); 28 // 注意要加1 29 var month = date.getMonth()+1; 30 var today = date.getDate(); 31 var arr = [‘星期日‘,‘星期一‘,‘星期二‘,‘星期三‘,‘星期四‘,‘星期五‘,‘星期六‘]; 32 // 获取当前星期里的第几天 33 var i = date.getDay(); 34 var day = arr[i]; 35 return ‘今天是:‘+year+‘年‘+month+‘月‘+today+‘日‘+day; 36 } 37 </script> 38 </body> 39 </html>