网站建设时经常需要用到一些JS配合,时间相减也是最常用到的JS代码之一,安舟网络对此作了一下小整理.

 //调用 date1-date2
    var mytime= dateDiff('2011-12-29 10:20:56','2011-12-30 14:13:25');

    //时间相减少方法(主方法)
    function dateDiff(date1, date2){
        var getTime1=stringToTime(date1,'getTime');
        var getTime2=stringToTime(date2,'getTime');
        if(getTime2>getTime1)
           return "暂无数据";
       
        var lstSec=(getTime1-getTime2)/1000;
        var showtime= formatSeconds(lstSec);
       
        return showtime;//结果是秒
    }
   
    //字符串转成Time(dateDiff)所需方法
    function stringToTime(string,timeType){
        var f = string.split(' ', 2);
        var d = (f[0] ? f[0] : '').split('-', 3);
        var t = (f[1] ? f[1] : '').split(':', 3);
        var mydate= (new Date(
        parseInt(d[0], 10) || null,
        (parseInt(d[1], 10) || 1)-1,
        parseInt(d[2], 10) || null,
        parseInt(t[0], 10) || null,
        parseInt(t[1], 10) || null,
        parseInt(t[2], 10) || null
        ));
       
        if(timeType=="getSeconds")
           return mydate.getSeconds();
        else if(timeType=="getMinutes")
           return mydate.getMinutes();
        else if(timeType=="getHours")
           return mydate.getHours();
        else if(timeType=="getTime")
           return mydate.getTime();
        else
           return mydate;
    }

    //格式化秒数为时分秒
    function formatSeconds(seconds) { 
         if(seconds >0){ 
             var minutes = Math.floor(seconds/60); 
             seconds = seconds - minutes * 60; 
             return formatMinutes(minutes) + (seconds > 0 ? seconds + "秒" : ""); 
         } 
         return seconds; 
    }

    //格式化分钟为时分 
    function formatMinutes(minutes){ 
         var day = parseInt(Math.floor(minutes / 1440)); 
         var hour = day >0?Math.floor((minutes - day*1440)/60):Math.floor(minutes/60); 
         var minute = hour > 0 ? Math.floor(minutes -day*1440 - hour*60):minutes; 
         var time=""; 
         if (day > 0) time += day + "天"; 
         if (hour > 0) time += hour + "小时"; 
         if (minute > 0) time += minute + "分钟"; 
         return time; 
    }