Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
To calculate the difference between two dates in Years, Months, Days, Hours, Minutes, Seconds, Milliseconds using JavaScript / TypeScript
dateDifference(actualDate, value: boolean) {
// Calculate time between two dates:
const date1 = actualDate; // the date you already commented/ posted
const date2: any = new Date(); // today
let r = {}; // object for clarity
let message: string;
const diffInSeconds = Math.abs(date2 - date1) / 1000;
const days = Math.floor(diffInSeconds / 60 / 60 / 24);
const hours = Math.floor(diffInSeconds / 60 / 60 % 24);
const minutes = Math.floor(diffInSeconds / 60 % 60);
const seconds = Math.floor(diffInSeconds % 60);
const milliseconds =
Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);
const months = Math.floor(days / 31);
const years = Math.floor(months / 12);
// the below object is just optional
// if you want to return an object instead of a message
r = {
years: years,
months: months,
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
milliseconds: milliseconds
};
// check if difference is in years or months
if (years === 0 && months === 0) {
// show in days if no years / months
if (days > 0) {
if (days === 1) {
message = days + ' day';
} else { message = days + ' days'; }
} else if (hours > 0) {
// show in hours if no years / months / days
if (hours === 1) {
message = hours + ' hour';
} else {
message = hours + ' hours';
}
} else {
// show in minutes if no years / months / days / hours
if (minutes === 1) {
message = minutes + ' minute';
} else {message = minutes + ' minutes';}
}
} else if (years === 0 && months > 0) {
// show in months if no years
if (months === 1) {
message = months + ' month';
} else {message = months + ' months';}
} else if (years > 0) {
// show in years if years exist
if (years === 1) {
message = years + ' year';
} else {message = years + ' years';}
}
// To display either an object or a message in the view
if (value === true) {
return r;
}
return message;
}
/* Sample Output
For example, consider a user X commented/posted something on any forum / facebook on Mon Jul 30 2018 12:08:00 GMT-0400 (Eastern Daylight Time)
Difference between Tue Jul 31 2018 13:11:04 GMT-0400 (Eastern Daylight Time) and the posted time of user X comment/post in simple message is "Posted 1 day ago"
Difference between now and the posted time of user X comment/post in detail object is "0 years, 0 months, 1 days, 1 hours, 3 minutes, 4 seconds, 613 milliseconds ago"
You can view this code written only in javascript here [https://code.sololearn.com/W2zBQeA8j595]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.