您的位置:首页 > Web前端 > JavaScript

基于js对时间动态控制显示。

2009-09-10 12:19 513 查看
最近项目中使用有个需求是按照流程挂起时间开始 进行统计,时间过去多久了 显示格式XX天XX小时XX分XX秒,后台已有该流程挂起时间。需要动态刷新时间,只能使用javascript对时间进行即使显示了。

为了提高代码的复用性,写了基于面向对象的 对时间控制的类。代码如下:

//Time对象
function TimeCom(Value)
{
var newCom = new Date(value);
this.year = newCom.getYear();
this.month = newCom.getMonth()+1;
this.day = newCom.getDate();
this.hour = newCom.getHours();
this.minute = newCom.getMinutes();
this.second = newCom.getSeconds();
this.msecond = newCom.getMilliseconds();
this.week = newCom.getDay();
}
//对日期相减,并计算得出结果,返回两个时间的相差秒数
function DateDiff(begindate,enddate)
{
var TimeCom1 = new TimeCom(begindate);
var TimeCom2 = new TimeCom(enddate);
var result;
//转换为标准的格林尼治时间进行计算
return Math.round((Date.UTC(TimeCom1.year,TimeCom1.month-

1,TimeCom1.day,TimeCom1.hour,TimeCom1.minute,TimeCom1.second)-Date.UTC(TimeCom2.year,TimeCom2.month-

1,TimeCom2.day,TimeCom2.hour,TimeCom2.minute,TimeCom2.second))/1000);

}
//通过DateDiff返回的结果计算显示需要的数据
function TimeGet(Value)
{
var secondTotal=parseInt(Value)
this.day=Math.round(secondTotal/(60*60*24));
secondTotal=secondTotal%(60*60*24);
this.hour=Math.round(secondTotal/(60*60));
secondTotal=secondTotal%(60*60);
this.minute=Math.round(secondTotal/(60));
secondTotal=secondTotal%(60);
this.second=secondTotal;

}


为方便输出显示格式,我将显示代码分离在前台页面,代码如下:

//listID 是显示结果,time 流程挂起时间。
function DisplayTime(listID,Time)
{
var TimeNow=new Date();
var StopTime=new Date(Time);
var secondTotal= DateDiff(TimeNow,StopTime);
var timget=new TimeGet(secondTotal);
$(listID).html("<font color='red'>"+timget.day+"天"+timget.hour+"小时"+timget.minute+"分"+timget.second+"秒</font>");

}


至此,脚本上增加setInterval( "DisplayTime(显示控件id,挂起时间)",1000 );即可以使用了。

一个页面多个流程要挂起,只要传递对应的控件id,跟获取到对应的挂起时间就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: