Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Created February 11, 2020 07:41
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 isurfer21/7ef4bcbd71b1bec6accf8595f757b2e9 to your computer and use it in GitHub Desktop.
Save isurfer21/7ef4bcbd71b1bec6accf8595f757b2e9 to your computer and use it in GitHub Desktop.
Calculates the exact duration in between 2 given dates.
/*
DURATION
Calculates the exact duration in between 2 given dates.
Copyright (c) 2020 Abhishek Kumar.
Protected by Creative Commons license (CC BY 4.0).
@file duration.js
@author Abhishek Kumar
*/
const APP_VER = '1.0.0';
const MS_PER_DAY = 1000 * 60 * 60 * 24;
function dayDiff(a, b) {
let utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
let utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
let utc = Math.floor((utc2 - utc1) / MS_PER_DAY);
return utc;
}
function calcAge(days) {
let y = Math.floor(days / 365);
let m = Math.floor((days % 365) / 30);
let d = Math.floor((days % 365) % 30);
return `${y}y ${m}m ${d}d`;
}
function render(fromdate, todate) {
let diff = dayDiff(new Date(fromdate), new Date(todate));
let diffs = [
`${calcAge(diff)}`,
`${(diff / 365).toFixed(2)} years`,
`${(diff / 30).toFixed(2)} months`,
`${diff} days`,
`${(diff / 7).toFixed(2)} weeks`,
`${(diff * 24)} hours`,
`${(diff * 24 * 60)} minutes`,
`${(diff * 24 * 60 * 60)} seconds`,
];
return `${diffs.join('\n')}`;
}
export function duration(argv) {
if (argv.h || argv.help) {
return `
Calculates the exact difference in between 2 given dates.
Syntax:
duration [from-date] [to-date]
where,
[from-date] From date in YYYY-MM-DD format
[to-date] To date in YYYY-MM-DD format
Options:
-h --help show help options
-v --ver show version
`;
} else if (argv.v || argv.ver) {
return `DURATION (Version ${APP_VER})`;
} else if (argv._.length == 0) {
return `Missing both dates`;
} else if (argv._.length == 1) {
return `Missing another date`;
} else {
return render(argv._[0], argv._[1]);
}
}
@isurfer21
Copy link
Author

isurfer21 commented Feb 11, 2020

Production
Click to Install in WebShell
CDN supported CDN URL

Development
Click to Install in WebShell
CDN supported CDN URL

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