2014-04-12 110 views
0

我想在几秒钟内找到两个日期(或时间,不知道该怎么说)之间的差异。时差返回NaN

这里是代码:

var montharray = new Array ("Jan" , "Feb" , "Mar" , "Apr" , "May" , "Jun" , "Jul" , "Aug" , "Sept" , "Oct" , "Nov" , "Dec") 
function time_difference (yr,m,d,h,mins,sec){ 
var today = new Date(); 
var this_year = today.getYear(); 
if (this_year<1000) 
this_year+=1900; 
var this_month= today.getMonth(); 
var this_day=today.getDate(); 
var this_hour=today.getHours(); 
var this_mins=today.getMinutes(); 
var this_secs=today.getSeconds(); 
var today_string=montharray[this_month]+" "+this_day+", "+this_year+" "+this_hour+" "+this_mins+" "+this_secs; 
var disconnect_string=montharray[m-1]+" "+d+", "+yr+" "+h+" "+mins+" "+sec; 
var difference=(Math.round((Date.parse(disconnect_string)-Date.parse(today_string))/1000)*1) 
alert(difference); 
    } 
time_difference(2014,4,13,16,0,0) 

(在我的国家,当我问的问题时间为15:26)

但警报显示我的NaN。

,但是当我只用年,月,日返回预期的结果,1

一些错误的标点符号或...?

回答

1

我的jsfiddle是在这里:http://jsfiddle.net/naokiota/T2VV2/2/
我猜你会喜欢做的是这样的:

function time_difference (yr,m,d,h,mins,sec){ 

var t1 = new Date(yr,m-1,d,h,mins,sec); 
var t2 = Date.now(); 
var diff_msec = t1 - t2; 
var diff_seconds = parseInt(diff_msec/1000); 
var diff_minutes = parseInt(diff_seconds/60); 
var diff_hours = parseInt(diff_minutes/60); 

alert(diff_seconds+" seconds"); 
alert(diff_minutes+" minutes"); 
alert(diff_hours+" hours"); 

} 
time_difference(2014,4,13,16,0,0); 

希望这有助于。

+0

谢谢你,帮助!这可能是做我想做的最简单的方法。 – yamahamm

2

使用方法getTime。它以毫秒为单位返回日期的UNIX偏移量。

var date1= new Date(); 
var date2 = new Date("2013-01-01"); 

var difference = (date1.getTime() - date2.getTime())/1000; 

如果你不知道哪两个日期较早,您可以在结果使用Math.abs

difference = Math.abs(difference); 
+0

但是,如果我知道date2的确切h,分钟和秒? – yamahamm

+0

这只是一个例子。您可以根据需要以尽可能多的粒度构建日期,例如'新日期(“星期六2014年4月12日14:42:41 GMT + 0200(W.欧洲日光时间)”)' – mingos