javascript 两个日期相减

1
<script>
var sDate="2007-06-06";
var eDate="2007-07-07";
var sArr = sDate.split("-");
var eArr = eDate.split("-");
var sRDate = new Date(sArr[0], sArr[1], sArr[2]);
var eRDate = new Date(eArr[0], eArr[1], eArr[2]);
var result = (eRDate-sRDate)/(24*60*60*1000);
alert(result);
</script>

2
<script>
//说明:这里用了Math.ceil()函数,向上取整,即零头算一天,^_^
var   strDate1   =   "2004-09-17   03:03:00.0";
var   strDate2   =   "2004-09-18   04:05:00.0";
strDate1=strDate1.substring(0,strDate1.lastIndexOf(".")).replace(/-/g, "/ ");
strDate2=strDate2.substring(0,strDate2.lastIndexOf(".")).replace(/-/g, "/ ");
//去掉毫秒 把-替换成/ 如果不替换转成时间戳类型火狐会出问题
var   date1   =  Date.parse(strDate1);
var   date2   =  Date.parse(strDate2);
alert( "strDate2与strDate1相差 "+(date2-date1)/(60*60*1000)+ "小时 ")
</script>

3
function dateDiff(date1, date2) {
            var type1 = typeof date1, type2 = typeof date2;
            if (type1 == 'string')
                date1 = stringToTime(date1);
            else if (date1.getTime)
                date1 = date1.getTime();
            if (type2 == 'string')
                date2 = stringToTime(date2);
            else if (date2.getTime)
                date2 = date2.getTime();
            //alert((date1 - date2) / (1000*60*60));
            return (date1 - date2) / (1000 * 60 * 60*24); //结果是小时
        }
        //字符串转成Time(dateDiff)所需方法
        function stringToTime(string) {
            var f = string.split(' ', 2);
            var d = (f[0] ? f[0] : '').split('-', 3);
            var t = (f[1] ? f[1] : '').split(':', 3);
            return (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
            )).getTime();


        }
       t=dateDiff("2007-02-11","2007-01-08");
       alert(t);

 

你可能感兴趣的:(JavaScript)