您好,登錄后才能下訂單哦!
本文實例講述了JavaScript時間日期操作。分享給大家供大家參考,具體如下:
本來想在網上找一些js實例來練練手,結果發現一本書《突破JavaScript編程實例五十講》,看了下內容還不錯,就下了下來;
后面又下了該書籍的源碼,一看才發現這本書編的日期是2002年的,代碼運行之后,有些代碼可以運行,有些代碼已經失效,原因是其所用的一些語言是已經淘汰的了。
其次就是由于是很早之前寫的,那時候可能還沒有css,js,html分離的想法,都是雜糅在一起的,看起來很不舒服。
還有就是,代碼末尾都是不帶分號的,還有各種不加關鍵字var的隱性全局變量等,都影響了程序的整潔性,簡潔性。
于是就想,要不我把他的代碼重新編寫,來實現書中的要求。
在此,也對該書的作者馬健兵等編著表示致敬,感謝他們的辛苦編著。
由于空間的限制,就不將js,css以單獨文件存儲了,全部都在html文件中,但已分離。
1、指定位置的時鐘顯示
時鐘始終顯示在網頁的正中間,12小時制。
效果圖:
源代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>指定位置的時鐘</title> <style> body{ font-size: 30px; font-family: Arial; background: #fef4d9; } #Current-time{ color:#66ff00; font-size: 30px; } #liveclock{ position:absolute; top:50%; left: 50%; width: 250px; height: 100px; margin: -50px 0 0 -125px; } p{ text-align: center; color:#ff00ff; margin: 0px; } </style> </head> <body> <div id="liveclock" > <div id="show"></div> </div> <script > function display() { var Digital=new Date(); var hours=Digital.getHours(); var minutes=Digital.getMinutes(); var seconds=Digital.getSeconds(); var dn="AM"; if(hours>12) //改成12小時制的 { dn="PM"; hours=hours-12; } if(hours==0) hours=12; if(minutes<=9) minutes="0"+minutes; //改成兩位數的顯示 if(seconds<=9) seconds="0"+seconds; var myclock="<b><p id='Current-time'>Current time is:</p><p>"+hours+":"+minutes+":"+seconds+" "+dn+"</p></b>"; var liveclock=document.getElementById("liveclock"); liveclock.innerHTML=myclock; setTimeout("display()",1000); } display(); </script> </body> </html>
2、表針式時鐘
由于書上的代碼太老了,看不懂,自己重新寫了一份。效果圖如下:
源代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>表針式時鐘</title> <style> body{ background: #fef4d9; } #time{ position: absolute; width: 212px; height: 216px; top:50%; left: 50%; margin: -108px 0 0 -106px; border: 2px solid yellow; } .timeNum{ position: absolute; } #pt0{ position: absolute; top:20px; left: 105px; border: 4px solid red; height: 90px; z-index: 1px; } #pt1{ position: absolute; top:35px; left: 105px; border: 4px solid blue; height: 75px; z-index: 100px; } #pt2{ position: absolute; top:50px; left: 105px; border: 4px solid yellow; height: 60px; z-index: 110px; } </style> </head> <body> <div id="time"> <div id="c0" class="timeNum" > </div> <div id="c1" class="timeNum"><b>1</b></div> <div id="c2" class="timeNum"><b>2</b></div> <div id="c3" class="timeNum"><b>3</b></div> <div id="c4" class="timeNum"><b>4</b></div> <div id="c5" class="timeNum"><b>5</b></div> <div id="c6" class="timeNum"><b>6</b></div> <div id="c7" class="timeNum"><b>7</b></div> <div id="c8" class="timeNum"><b>8</b></div> <div id="c9" class="timeNum"><b>9</b></div> <div id="c10" class="timeNum"><b>10</b></div> <div id="c11" class="timeNum"><b>11</b></div> <div id="c12" class="timeNum"><b>12</b></div> <div id="pt0" > </div> <div id="pt1" ></div> <div id="pt2" ></div> </div> </body> <script language=javascript> function getid(id){ return document.getElementById(id); } //將數字以圓形的形式顯示在屏幕上。根據三角函數的計算 function clockNum(){ for (var i=1; i<13;i++){ var c1=getid("c"+i); angle=i*30/360*Math.PI*2; c1.style.top=0+(100-Math.cos(angle)*100)+"px"; c1.style.left=100+Math.sin(angle)*100+"px"; } } function clockRotate(){ //獲取當前的時間 var start= new Date(); var H=start.getHours(); var M=start.getMinutes(); var S=start.getSeconds(); //設置其旋轉的角度,分針每次6度,秒針每次6度,時針每次0.5度 var mDu=M*6; var hDu=M*0.5+H*30; var sDu=S*6; var pt0=getid("pt0"); var pt1=getid("pt1"); var pt2=getid("pt2"); //設置其繞末端旋轉,寬度是在中間,高度是在整個高度的末尾,采用百分數的形式 pt0.setAttribute('style',''+'transform:rotate('+ sDu +'deg); '+'transform-origin: center 93%;'); pt1.setAttribute('style',''+'transform:rotate('+ mDu +'deg); '+'transform-origin: center 94%;'); pt2.setAttribute('style',''+'transform:rotate('+ hDu +'deg); '+'transform-origin: center 95%;'); } //每隔1毫秒檢測一次 setInterval(clockRotate,100); function init(){ clockNum(); } init(); </script> </html>
3、帶按鈕開關的form時鐘
采用按鈕的形式進行控制,按下開,顯示時間和日期,按下關,則清空。效果圖如下
源代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>帶按鈕開關的Form時鐘</title> <style> body{ background: #aebcdf; } form{ position:absolute; left:50; top:50; z-index:5; } input{ color:red; } input[type="text"]{ color: black; } .center{ position: absolute; top:50%; left: 50%; transform: translate(-50%, -50%); border: 2px solid yellow; width: 220px; height: 42px; padding: 10px; } </style> </head> <body> <div class="center"> <form name="clock" > <input type="text" name="disp" value="" size=30 onFocus="this.blur()" ><br> <input type="button" name="rad" value="off" id="offbtn" >關 <input type="button" name="rad" value=" on" id="onbtn">開 </form> <div> </body> <script> //公共事件 var common={ //獲取id getid:function (id){ return document.getElementById(id); }, //綁定事件 on:function (element,eventName,listener){ if (element.addEventListener){ element.addEventListener(eventName,listener,false); } else if (element.attachEvent){ element.attachEvent('on'+eventName,listener); } else element['on'+eventName]=listener; }, } //時間的方法與屬性 var time={ //用來標記是開還是關,0表示關 enabled:0, //存儲星期 day:["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], //設定和顯示時間 //注意中間用了toLocaleString(); Time_Set:function () { var today = new Date(); TM=window.setTimeout('time.Time_Set()', 1000); var timeStr=today.toLocaleString()+" "+time.day[today.getDay()]; document.clock.disp.value = timeStr; console.log(today.toLocaleString()); }, } //全局定時函數名字 var TM; //點擊開事件 var onbtn=common.getid("onbtn"); common.on(onbtn,'click',function(){ if(time.enabled == 0) { time.Time_Set(); time.enabled = 1; } }); //點擊關事件 var offbtn=common.getid("offbtn"); common.on(offbtn,'click',function(){ if( time.enabled==1 ) { document.clock.disp.value=''; clearTimeout( TM ); time.enabled = 0; } }); </script> </html>
4、年齡提示器
網頁打開時依次彈出3個輸入對話框,分別需要你輸入你的出生日期(年月日),然后顯示內容,顯示你的出生年月,距離下一次你的生日還有多少時間,以及你活了多少時間。效果圖:
源代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>年齡提示器</title> <style> div{ position: absolute; top:50%; left: 50%; transform:translate(-50%,-50%); width: 375px; height: 200px; border: 2px solid red; padding: 20px; } p{ margin: 0; margin-bottom: 10px; } input{ margin-bottom: 10px; } </style> </head> <body bgcolor="f9fcb6" > <div> <form> <p id="birday"></p> <p id="age"></p> <input type="text" name="nextYear" size="47" value=""> <p>I've been alive for...</p> <input type="text" name="liveYear" size="47" value=""> <p>您已在本站停留了</p> <input type=text name="input1" size=10 value=""> <br> </form> </div> </body> <script > function getid(id){ return document.getElementById(id); } var timerID=window.setTimeout("showtime()",1); //彈出輸入框,獲取用戶的出生日期,注意要把日期轉化為數字 var bMonth =parseInt(prompt('Which month were you born in?(月份)','1-12')); var bDate =parseInt(prompt('Which day were you born on?(天)','1-31')); var bYear =parseInt(prompt('Which year were you born in?(年份)','1900-'+new Date().getFullYear())); var tMonth = ['January','February','March','April','May','June','July','August','September','October','November','December']; var corrMonth = tMonth[bMonth-1]; getid("birday").innerHTML=" I was born <b>"+corrMonth+", "+bDate+", "+bYear+"</b>. (<b>"+bMonth+"/"+bDate+"/"+bYear+"</b>)"; //傳入格式化后的時間,用來計算兩個時間差,nextAgeDay > today function computeTime(nextAgeDay,today){ var day={}; var liveSec=nextAgeDay.getTime(); var lTime = today.getTime(); var daysec=24*60*60*1000; var hoursec=60*60*1000; var minsec=60*1000; var tt=(-lTime+liveSec); //計算時間差,天,小時,分,秒 day._1day=Math.floor(tt/daysec); day._1hour=Math.floor((tt-day._1day*daysec)/hoursec); day._1min=Math.floor((tt-day._1day*daysec-day._1hour*hoursec)/minsec); day._1sec=Math.floor((tt-day._1day*daysec-day._1hour*hoursec-day._1min*minsec)/1000); return day; } //計算距離下一歲還有多少天的時候,可以采用與現在的秒數相減getTime; function showtime() { //獲取當前日期 var today = new Date(); var month = today.getMonth() + 1; var date = today.getDate(); var year = today.getFullYear(); //計算下一次生日是哪一年 var nextAgeYear; var yourAge = year - bYear; if (bMonth < month || ((bMonth == month) && (date > bdate))) { yourAge--; nextAgeYear=year+1; } else { nextAgeYear=year; } //下一年幾歲 var nextAge = yourAge + 1; //將下一次生日時間格式化,默認時間在00:00;計算距離下一次生日還還有多長時間 var nextAgeDay = new Date(""+nextAgeYear+","+bMonth+", "+bDate+" , 00:00"); var day=computeTime(nextAgeDay,today); //將出生日期時間格式化,默認時間在00:00;計算已經活了多久了 var bornAgeDay = new Date(""+bYear+","+bMonth+", "+bDate+" , 00:00"); var lday=computeTime(today,bornAgeDay); //將結果輸出 document.forms[0].nextYear.value =""+day._1day+"days, "+day._1hour+"hours, "+day._1min+"minutes, "+day._1sec+"seconds"; getid("age").innerHTML=" I am <b>"+yourAge+"</b> years old, and will turn <b>"+nextAge+"</b> in:"; document.forms[0].liveYear.value =""+lday._1day+"days, "+lday._1hour+"hours, "+lday._1min+"minutes, "+lday._1sec+"seconds"; timerID = window.setTimeout("showtime()",1000); } //第三個輸入框,計算停留時間 var sec=0; var min=0; var hou=0; var idt=window.setTimeout("update();",1); function update() { if(sec==60){sec=0;min+=1;} if(min==60){min=0;hou+=1;} document.forms[0].input1.value=hou+"時"+min+"分"+sec+"秒"; idt=window.setTimeout("update();",1000); sec++; } </script> </html>
5、得到文件的最后修改時間
本節主要講獲取HTML文件的最后修改時間。效果如下,其實跟前面的例子很像。
源代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>獲得文件的最后修改時間</title> <style> body{ background: yellow; } .center{ position: absolute; top:50%; left: 50%; transform:translate(-50%,-50%); width: 300px; height: 110px; border: 2px solid red; padding: 10px; } p{ text-align: center; margin: 0px; padding: 10px; } </style> </head> <body> <script> //獲得文件的格式化最后修改時間 function DocDate() { var StrofLastMod = document.lastModified; //獲得文件的最后修改時間,它是一個string類型的變量。 var months = ["January","February","March","April","May","June","July","August", "September","October","November","December"]; //月份名變量,供轉換。 var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];//星期名變量,供轉換 var c = ":"; //用來分隔時,分,秒。 var mdate =new Date(StrofLastMod); var month = months[mdate.getMonth()]; var date = mdate.getDate(); var year = mdate.getFullYear(); var day = days[mdate.getDay()]; var minutes=mdate.getMinutes(); var hours= mdate.getHours(); var seconds=mdate.getSeconds(); var miliSec=mdate.getMilliseconds(); var dateStr = year+" "+month+" "+date+" "+day+" "+hours+c+minutes+c+seconds+"."+miliSec; //獲得格式化的文件最后修改時間。 return dateStr; } var div=document.createElement("div"); div.className="center"; var divson=document.createElement("div"); divson.innerHTML="<p>This File is last updated at:</p><p>"+DocDate()+"</p><p>"+document.lastModified+"</p>"; div.appendChild(divson); document.body.appendChild(div); </script> </body> </html>
PS:這里再為大家推薦幾款比較實用的天數計算在線工具供大家使用:
在線日期/天數計算器:
http://tools.jb51.net/jisuanqi/date_jisuanqi
在線日期計算器/相差天數計算器:
http://tools.jb51.net/jisuanqi/datecalc
在線日期天數差計算器:
http://tools.jb51.net/jisuanqi/onlinedatejsq
在線天數計算器:
http://tools.jb51.net/jisuanqi/datejsq
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript時間與日期操作技巧總結》、《JavaScript+HTML5特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。