Skip to content

Instantly share code, notes, and snippets.

@timw4mail
Created February 8, 2013 21:59
Show Gist options
  • Save timw4mail/4742282 to your computer and use it in GitHub Desktop.
Save timw4mail/4742282 to your computer and use it in GitHub Desktop.
Bookmarket for calculating time differences
javascript:(function(doc){
"use strict";
var $ = function(id){
return doc.getElementById(id);
};
var html = '<div id="tc_form_wrapper"> \
<input type="number" id="tch1" size="3" /> : <input type="number" id="tcm1" size="3" /> \
<button id="tc_plus">+</button> \
<button id="tc_min">-</button> \
<input type="number" id="tch2" size="3" /> : <input type="number" id="tcm2" size="3" /> \
= \
<span id="tc_out"></span> \
<div style="float:right"> \
<button id="tc_clear">Clear</button> \
<button id="tc_close"> X </button> \
</div> \
</div>';
doc.getElementsByTagName('body')[0].insertAdjacentHTML('afterbegin', html);
var hour1 = $('tch1'),
hour2 = $('tch2'),
min1 = $('tcm1'),
min2 = $('tcm2'),
output = $('tc_out');
// Clear
$('tc_clear').onclick = function() {
hour1.value = "0";
hour2.value = "0";
min1.value = "00";
min2.value = "00";
output.innerHTML = "";
};
// Remove
$('tc_close').onclick = function() {
doc.getElementsByTagName('body')[0].removeChild($('tc_form_wrapper'));
};
// Add times
$('tc_plus').onclick = function() {
var hours = parseInt(hour1.value, 10) + parseInt(hour2.value, 10);
var mins = parseInt(min1.value, 10) + parseInt(min2.value, 10);
while(mins > 59)
{
hours += 1;
mins -= 60;
}
output.innerHTML = "Total: "+hours+":"+mins;
};
// Subtract times
$('tc_min').onclick = function() {
var h1 = parseInt(hour1.value, 10),
h2 = parseInt(hour2.value, 10),
m1 = parseInt(min1.value, 10),
m2 = parseInt(min2.value, 10),
hours = 0,
mins = 0;
// Create sane hour/minute groups
while(m1 > 59)
{
h1 += 1;
m1 -= 60;
}
while(m2 > 59)
{
h2 += 1;
m2 -= 60;
}
// If we have to "borrow" hours
if ((m1 - m2) < 0)
{
// Borrow from the bigger hours
if (h1 > 0)
{
h1 -= 1;
m1 += 60;
hours = h1 - h2;
mins = m1 - m2;
}
}
else
{
hours = h1 - h2;
mins = m1 - m2;
}
output.innerHTML = "Difference: "+hours+":"+mins;
};
// Set values correctly
$('tc_clear').onclick();
}(document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment