Skip to content

Instantly share code, notes, and snippets.

@Jevin23

Jevin23/time_diff.js

Last active Feb 5, 2017
Embed
What would you like to do?
calc time diff, node time_diff.js 2:30:00 5:30:00, will output: 03:00:00
#!/usr/bin/env node
if (!process.argv[2] || !process.argv[3]) {
console.log('usage node time_diff hh:mm:ss hh:mm:ss');
process.exit(1);
}
const timeToSec = (time) => time.split(':').reduce((acc, v) => acc * 60 + parseInt(v), 0);
const diffInSeconds = (time1, time2) => timeToSec(time2) - timeToSec(time1);
const hhmmss = (secs) => {
var minutes = Math.floor(secs / 60);
secs = secs % 60;
var hours = Math.floor(minutes / 60);
minutes = minutes % 60;
return pad(hours) + ":" + pad(minutes) + ":" + pad(secs);
function pad(num) {
return ("0" + num).slice(-2);
}
};
try {
console.log(hhmmss(diffInSeconds(process.argv[2], process.argv[3])));
}
catch (err) {
console.log('usage node time_diff hh:mm:ss hh:mm:ss');
process.exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment