当前位置:主页 > 网页前端 > JavaScript代码 >

JavaScript时间日期操作实例小结【5个示例】

时间:2022-07-01 09:47:36 | 栏目:JavaScript代码 | 点击:

本文实例讲述了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程序设计有所帮助。

您可能感兴趣的文章:

相关文章