Last active
February 5, 2017 23:49
-
-
Save Jevin23/6f9c6ed5ed32260be5ccffa30145e14e to your computer and use it in GitHub Desktop.
calc time diff, node time_diff.js 2:30:00 5:30:00, will output: 03:00:00
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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