Skip to content

Instantly share code, notes, and snippets.

@ltpitt
Last active February 27, 2017 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ltpitt/7e2e38d4142dcb5872ab0d77793f2e64 to your computer and use it in GitHub Desktop.
Save ltpitt/7e2e38d4142dcb5872ab0d77793f2e64 to your computer and use it in GitHub Desktop.
Javascript function that calculates the difference between two datetime in hours
/**
* Calculates the difference between two datetime in hours
* @param {String} Current datetime (any format compatible with Date)
* @param {String} Start datetime (any format compatible with Date)
* @return {Integer} The difference between Current datetime and Start datetime in hours
*/
function calculateDatetimeDeltaHours(datetimeCurrent, datetimeStart) {
var datetimeCurrent = new Date(datetimeCurrent);
var datetimeStart = new Date(datetimeStart);
var deltaHours = Math.abs(datetimeCurrent - datetimeStart) / 36e5
return deltaHours;
}
// In the following example I put into deltaHours variable the return of calculateDatetimeDeltaHours function
var deltaHours = calculateDatetimeDeltaHours("04/13/2015 12:04:02", "04/13/2015 11:04:02");
// Then I print the difference, in hours, between the two timestamps
console.log(deltaHours);
@ltpitt
Copy link
Author

ltpitt commented Nov 29, 2016

You can try the code here:
https://jsfiddle.net/0opfanfL/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment