Skip to content

Instantly share code, notes, and snippets.

@IvanAdmaers
Created November 24, 2022 18:56
Show Gist options
  • Save IvanAdmaers/a272bf71bba48681ed0985eb56aace0d to your computer and use it in GitHub Desktop.
Save IvanAdmaers/a272bf71bba48681ed0985eb56aace0d to your computer and use it in GitHub Desktop.
Get time difference between two dates JavaScript | JS | TS
import { getTimeDifferenceBetweenTwoDates } from './getTimeDifferenceBetweenTwoDates';
describe('getTimeDifferenceBetweenTwoDates', () => {
it('should return a correct result', () => {
const date1 = new Date(
'Thu Nov 24 2022 13:50:50 GMT-0500 (Eastern Standard Time)'
);
const date2 = new Date(
'Thu Nov 25 2022 13:50:50 GMT-0500 (Eastern Standard Time)'
);
const hours = 24;
const minutes = hours * 60;
const seconds = minutes * 60;
expect(getTimeDifferenceBetweenTwoDates(date2, date1).hours).toBe(
hours
);
expect(getTimeDifferenceBetweenTwoDates(date2, date1).minutes).toBe(
minutes
);
expect(getTimeDifferenceBetweenTwoDates(date2, date1).seconds).toBe(
seconds
);
});
});
export const getTimeDifferenceBetweenTwoDates = (date1: Date, date2: Date) => {
const difference = (date2.getTime() - date1.getTime()) / 1000;
const hours = Math.abs(Math.round(difference / 60 / 60));
const minutes = Math.abs(Math.round(difference / 60));
const seconds = Math.abs(Math.round(difference));
return {
hours,
minutes,
seconds,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment