简体   繁体   中英

How to calculate difference between two datetime in javascript?

I am using telerik controls and i want difference between two datetime variables how can i calculate.

var x=9/1/2012 10:20:00 AM;
var y=9/1/2012 09:00:00 AM;

I want difference between two times throw javascript in to another variable as number.

Create two Date type variable and then calculate the difference using - operator, you will get difference in milliseconds.

var first = new Date(2012,8,1,10,20,0,0); 
var second = new Date(2012, 9, 1, 09, 00, 0, 0); 
var difference = (second - first); // difference in milliseconds

Here is working demo

You should try something on these lines

var a = new Date('9/1/2012 10:20:00 AM');
var b = new Date('9/1/2012 09:00:00 AM');
// a - b  this should give you the diff
var diff = a - b;
alert(diff/1000); // this should be value in seconds i.e 4800

See this

Basically, put those two dates into Date objects, and subtract one from the other. That will give you the difference in milliseconds and you can work from there to get larger time segments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM