Jinbom Heo
Jinbom Heo

Reputation: 7400

How to perform date subtraction in javascript

It's a little complicated to calculate delta time in js. this is the pseudo-code,

var atime = "2010-12-05T08:03:22Z";
var btime = "2010-01-11T08:01:57Z"

var delta_time = btime - atime; 
delta_time ?

I want to know exact date time between two time inputs. is there any easy way to find out delta time?

Upvotes: 20

Views: 33260

Answers (2)

pdu
pdu

Reputation: 10413

A Date / Time object displays a time in a current situation (e.g. now() ). Displaying a difference of time is not part of a Date or Time object because the difference between e.g. May 1 and May 3 would result in, maybe, January 3, 1970, or maybe May 2, depends on how you start counting your delta on.

I would suggest putting your times into a timestamp which is a simple int in seconds. Do some substraction and voilá, there's your delta seconds. This delta can be used to apply to any other Object.

Upvotes: 6

David Hedlund
David Hedlund

Reputation: 129792

var atime = new Date("2010-12-05T08:03:22Z");
var btime = new Date("2010-01-11T08:01:57Z");

var delta_time = btime - atime; 

The value of delta_time will be the difference between the two dates in milliseconds.

If you're only interested in the difference, and don't care to differentiate between which is the later date, you might want to do

var delta_time = Math.abs(btime - atime);

Upvotes: 28

Related Questions