var date= new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); var WeekDay = date.getDay(); //獲取當前星期X(0-6,0代表星期天) var Hour = date.getHours(); //獲取當前小時數(0-23) var Minute = date.getMinutes(); // 獲取當前分鍾數(0-59) var Sec =date.getSeconds(); //獲取當前秒數(0-59)
獲得時間后這些小於10的默認前面沒有0,我們自定義一個加0的方法
function p(s) { return s < 10 ? '0' + s: s; }
然后將獲得的時間如下調用即可
//格式化時間 var str = year + '-' + p(month) + '-' + p(day); //寫入時間格式為 xxxx-xx-xx document.getElementById("div_ID").innerHTML = str;