womendu 发表于 2013-1-29 09:17:19

JAVASCRIPT 中 日期时间相减的方法(实用)

//JAVASCRIPT中 日期相减很麻烦 ,现在有现成的实现方法,拷贝过去就可以用了,方便
//调用该方法(主方法)   
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();   
return (date1 - date2) / 1000;//结果是秒   
}
//字符串转成Time(dateDiff)所需方法   
function stringToTime(string){   
var f = string.split(' ', 2);   
var d = (f ? f : '').split('-', 3);   
var t = (f ? f : '').split(':', 3);   
return (new Date(   
parseInt(d, 10) || null,   
(parseInt(d, 10) || 1)-1,   
parseInt(d, 10) || null,   
parseInt(t, 10) || null,   
parseInt(t, 10) || null,   
parseInt(t, 10) || null   
)).getTime();
}
//调用 dateDiff("2009-10-10 19:00:00","2009-10-10 18:00:00")
返回的是秒钟
页: [1]
查看完整版本: JAVASCRIPT 中 日期时间相减的方法(实用)