/* * 一、按照格式xxxx年xx月xx日 xx時xx分xx秒 顯示當前時間,要求不滿10的在前補0。 * 二、自定義一函數,輸出N天后的日期。 * 三、自定義一函數,實時顯示當前時間,格式「xxxx年xx月xx日 xx時xx分xx秒 星期x」。 * 四、計算兩個日期對象相差的天數。 * 五、轉換爲:yyyy-MM-dd HH:mm:ss格式 */ window.onload=function(){ //1 var txt = document.getElementById("showtime"); setInterval(function(){ //獲取時間 var data = new Date(); var Y = data.getFullYear(), M = data.getMonth()+1, D = data.getUTCDate(), h = data.getHours(), m = data.getMinutes(), s = data.getSeconds(); //時間補0 function p(s){ return s<10 ? '0' + s : s; } txt.innerHTML = "當前時間:"+Y+"年"+ p(M)+"月"+ p(D)+"日"+ p(h)+"小時"+ p(m)+"分鐘"+ p(s)+"秒鐘" },1000) //2 // function calculation(t){ // var dato = new Date(); // var Y = dato.getFullYear(), // M = dato.getMonth()+1, // D = dato.getUTCDate()+t; // function p(s){ // return s<10 ? '0'+s : s; // } // var count = document.getElementById("count"); // count.innerHTML = t+"天后的時間是"+Y+"年"+p(M)+"月"+p(D)+"日" // } // calculation(9) function getday(day){ var today = new Date(); //獲取截止到當前的時間戳,加上傳入天數的毫秒數,算出一共的毫秒數,再分別設置時間 var tmill = today.getTime()+1000*60*60*24*day; today.setTime(tmill); var Y = today.getFullYear(), M = today.getMonth()+1, D = today.getDate(), qh= day function mchange(s){ return s<10 ? "0"+s:s } function c(f){ return f<0 ? "前": "後" } var count = document.getElementById("count"); count.innerHTML = day+"天"+c(qh)+"的時間是"+Y+"年"+mchange(M)+"月"+mchange(D)+"日" } getday(17) //3 var ntimetxt = document.getElementById("ntime"); setInterval(function(){ var ntime = new Date(); var Y = ntime.getFullYear(), M = ntime.getMonth()+1, D = ntime.getUTCDate(), x = ntime.getUTCDay(), h = ntime.getHours(), m = ntime.getMinutes(), s = ntime.getSeconds(); function p(t){ return t<10 ? '0'+t : t; } var xin = ["日","一","二","三","四","五","六"]; for (var i=0;i<xin.length;i++){ if(i===x){ x = xin[i] } } ntimetxt.innerHTML = "如今的時間是:"+Y+"年"+p(M)+"月"+p(D)+"日"+p(h)+"時"+p(m)+"分鐘"+p(s)+"秒"+"星期"+x; },1000) //4 function chaday(s1,s2){ var sdate1 = new Date(s1), sdate2 = new Date(s2); return (sdate2.getTime()-sdate1.getTime())/86400000; } var s1 = "2018-9-19", s2 = "2020-9-19" var cha = document.getElementById("cha") cha.innerHTML="從"+s1+"到"+s2+"相差"+chaday(s1,s2)+"天" Date.prototype.format = function(dat){ var date = new Date(); date.setTime(dat*1000); var Y = date.getFullYear(), M = date.getMonth(), D = date.getUTCDate(), h = date.getHours(), m = date.getMinutes(), s = date.getSeconds(); function p(e){ return e<10 ? "0"+e : e; } return Y+"-"+M+"-"+D+" "+h+":"+m+":"+s } var tran=document.getElementById("tran"); tran.innerHTML= new Date().format(1537350880) }