js 獲取系統時間:年月日 星期 時分秒(動態)


最近再寫一個純html頁面,有時間和天氣的數據,天氣后台給接口,時間要自己獲取,我就自己弄了下,

<div class="basic"></div>

這是放時間的div

//這是首次加載顯示的*************************   
var myDate = new Date(); var year = myDate.getFullYear();//獲取年 var month = myDate.getMonth() + 1;//獲取月,默認從0開始,所以要加一 var date = myDate.getDate();//獲取日 var hours = myDate.getHours();//獲取小時 var minutes = myDate.getMinutes();//獲取分 var seconds = myDate.getSeconds();//獲取秒 var weekend = myDate.getDay(); //獲取星期幾,這里獲得到的是數字1-7,所以我下面自己new了一個數組把獲取到的數字當下標 var weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"); var day = weeks[weekend]//這樣就是顯示的星期x了
  //這些if判斷是在小於10的時候前面自動補0
if (month<10) { month = '0'+month } if (date<10) { date = '0'+date } if (hours<10) { hours = '0'+hours } if (minutes<10) { minutes = '0'+minutes } if (seconds<10) { seconds = '0'+seconds }      $('.basic').append("<span class='year'>"+year+"-"+month+"-"+date+"</span>"+" ")//拼接年月日 $('.basic').append("<span class='hours'>"+hours+":"+minutes+":"+seconds+"</span>"+" ")//拼接時分秒 $('.basic').append("<span class='day'>"+day+"</span>"+" ")星期幾 //這里是每隔一秒調用一次改變時分秒的函數*********************************
  $(
function(){ setInterval("changeTime();",1000); //每隔一秒運行一次 }) function changeTime() { myDate = new Date(); year = myDate.getFullYear(); month = myDate.getMonth() + 1; date = myDate.getDate(); hours = myDate.getHours(); minutes = myDate.getMinutes(); seconds = myDate.getSeconds(); weekend = myDate.getDay(); weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"); day = weeks[weekend] if (month<10) { month = '0'+month } if (date<10) { date = '0'+date } if (hours<10) { hours = '0'+hours } if (minutes<10) { minutes = '0'+minutes } if (seconds<10) { seconds = '0'+seconds }
     //這里替換第一次加載的數據 $(
'.year').html(year+"-"+month+"-"+date) $('.hours').html(hours+":"+minutes+":"+seconds) $('.day').html(day) }

水平有限,就現在這里記錄一下吧


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM