通过原生JS来创建一个网站运行时间计时

来源:互联网 发布:mac管理安卓手机助手 编辑:程序博客网 时间:2024/06/11 08:45

javascript代码:

function runtime(startTime){    var endTime = new Date(startTime);    var nowTime = new Date();    var t = nowTime.getTime() - endTime.getTime();    var d=Math.floor(t/1000/60/60/24);    var h=Math.floor(t/1000/60/60%24);    var m=Math.floor(t/1000/60%60);    var s=Math.floor(t/1000%60);    var month=Math.ceil(d/30);    var year=Math.ceil(d/365);    document.getElementById("t_d").innerHTML=d;    document.getElementById("t_h").innerHTML=h;    document.getElementById("t_m").innerHTML=m;    document.getElementById("t_s").innerHTML=s;    document.getElementById("t_month").innerHTML=month;    document.getElementById("t_year").innerHTML=year;}    setInterval("runtime('2017/7/14 12:00:00')",1000);

HTML:

<blockquote class="blockquote-center" id="clear">            <div id="run">网站运行了:                <span style="font-weight:bold;"</span><br>                    <span id="t_d"></span><span id="t_h"></span><span id="t_m"></span><span id="t_s"></span><br>                <span id="run">今天是第<span id="t_month"></span>个月,第<span id="t_year"></span>年 !</span>              </div>        </blockquote>

样式:

.blockquote-center {              position: absoulte;              float: left;              margin: 0 auto;              padding: 0;              border-left: none;              width: 200px;              display: inline-block;              margin-top: 0px;              text-align: center;              background-color: #f5f7f9;}.blockquote-center::before,.blockquote-center::after {  position: absolute;  content: ' ';  display: block;  width: 100%;  height: 15px;  opacity: 0.2;  background-repeat: no-repeat;  background-position: 0 -6px;  background-size: 20px 20px;}.blockquote-center::before {  top: -20px;  border-top: 1px solid #ccc;}.blockquote-center::after {  bottom: -20px;  border-bottom: 1px solid #ccc;  background-position: 100% 8px;}.blockquote-center p {  text-align: center;}#run {  background: #f5f7f9;  margin: 0px auto;  text-align: center;  padding: 0px;  font-size: 15px;  color: #9a8c8c;}

日期对象可以储存任意一个日期,并且可以精确到毫秒数(1/1000 秒)。新建一个日期对象:var time=new Date();
也可以自定义事件:
var day = new Date(2017,7,14);
var day = new Date(‘Jul 1,2017’);

相关方法:

get/setDate():返回\设置日期;getFullYear():返回年份,四位数getYear():返回年份getMonth():返回月份getHours():返回小时,24小时getMinutes():返回分钟数getSeconds():返回秒钟数gettime():返回时间

ceil方法:四舍五入
setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。
setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。