当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript时间日期操作实例小结【5个示例】

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

2019年01月08日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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:这里再为大家推荐几款比较实用的天数计算在线工具供大家使用:

在线日期/天数计算器:

在线日期计算器/相差天数计算器:

在线日期天数差计算器:

在线天数计算器:

更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript时间与日期操作技巧总结》、《javascript+html5特效与技巧汇总》、《javascript错误与调试技巧总结》、《javascript数据结构与算法技巧总结》及《javascript数学运算用法总结

希望本文所述对大家javascript程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网