Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 618
Jinbom Heo Avatar asked Feb 22 '11 07:02

Jinbom Heo


People also ask

Can you subtract date in JavaScript?

To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days. JavaScript date setDate() method sets the day of the month for a specified date according to local time.

How do you subtract days from new date?

You can use d. setDate(d. getDate() + days) with both positive and negative values for days to add and subtract days respectively.

How do you subtract time in JavaScript?

To subtract hours from a date: Use the getHours() method to get the hours of the specific date. Use the setHours() method to set the hours for the date.

How do you subtract dates in TypeScript?

To calculate the time between 2 dates in TypeScript, call the getTime() method on both dates when subtracting, e.g. date2. getTime() - date1. getTime() .


2 Answers

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);
like image 74
David Hedlund Avatar answered Sep 28 '22 04:09

David Hedlund


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.

like image 27
pdu Avatar answered Sep 28 '22 04:09

pdu