js时间间隔和倒计时

var commom={};
commom.interval=function(timestr)
{
	var timestr=countTime(timestr);
	if(timestr>=0)
	{
		if (sencond_dif < 60) 
        {
            time_str = "刚刚";
        }
        else if (sencond_dif < 60*60) {
            time_str = parseInt(sencond_dif/60)+'分钟前';
        }
        else if (sencond_dif < 60*60*24) {
            time_str = parseInt(sencond_dif/3600)+'小时前';
        }
        else if (sencond_dif < 60*60*24*30) {
            time_str = parseInt(sencond_dif/86400)+'天前';
        }
        else if (sencond_dif<60*60*24*30*12)
        {
          time_str = parseInt(sencond_dif/2592000)+'个月前';
        }
        else
        {
            time_str ='很久之前';
        }
	}
	else
	{
		time_str='时间参数错误,大于当前时间';
	}
	return time_str;
}
commom.countdown_clear=false;
commom.countdown=function(obj)
{
	var arr=[],time_str='';
    var timestr=-countTime(obj.timestr);
    if(timestr>0)
    {
        time_str=parseInt(timestr/3600)>9 ? parseInt(timestr/3600).toString()+":" : "0"+ parseInt(timestr/3600).toString()+":";
        time_str+=parseInt(timestr%3600/60)>9 ? parseInt(timestr%3600/60).toString()+":" : "0"+parseInt(timestr%3600/60).toString()+":";
        time_str+=parseInt(timestr%3600%60)>9 ? parseInt(timestr%3600%60).toString() :"0"+parseInt(timestr%3600%60).toString();
    }
    else
    {
        time_str=obj.describe!==undefined?obj.describe:'已结束';
        commom.countdown_clear=true;
    }
    arr=time_str.split(':');
    return obj.type!==undefined && obj.type==1 ? arr:time_str; 
}
//返回时间差
function countTime(strDate)
{
	//字符串转换为时间
	var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/,
    function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');

    var datenow,time_dif,time_str,eval_str;
    var arr=new Array(),
        i=0;

    datenow=new Date();
    // 秒数 如果是 datanow.getTime()-data.getTime(),这个是毫秒数
    sencond_dif=parseInt((datenow.getTime()-date.getTime())/1000);

    return sencond_dif;
}

调用方式

// console.log(commom.interval('2015-06-16 18:00:00'));
// setInterval(function(){console.log(commom.countdown({timestr:'2015-06-25 18:00:00',type:1}));},1000);

注:在调用倒计时,返回的字段可以是字符串,也可以通过传type:1来选择返回一个"[ 时,分,秒 ]"的一个数组,默认是返回“时分秒字符串”。


目前代码是这样子,有改进的地方或者更好的一个写法,还请大家指点!!!!笔者先谢过!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值