Skip to content

Instantly share code, notes, and snippets.

@dlski
Last active February 23, 2018 15:03
Show Gist options
  • Save dlski/51ad4cecbdf4ef7cbcd2ecaa0f1f7e5a to your computer and use it in GitHub Desktop.
Save dlski/51ad4cecbdf4ef7cbcd2ecaa0f1f7e5a to your computer and use it in GitHub Desktop.
[Google Spreadsheets Script] Simple time tracking
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Time tracking')
.addItem('Setup', 'setupSpreadsheet')
.addItem('Start task', 'startTask')
.addItem('End task', 'endTask')
.addToUi();
}
function durationFormula(rowNo) {
return "=(D" + rowNo + " + E" + rowNo + ") - (B" + rowNo + " + C" + rowNo + ")"
}
function setupSpreadsheet() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
// set date format
var dateValidation = SpreadsheetApp
.newDataValidation()
.requireDate()
.build();
[
sheet.getRange("B:B"),
sheet.getRange("D:D")
].forEach(function (range) {
range
.setNumberFormat("yyyy-mm-dd")
.setDataValidation(dateValidation);
});
// set time format
[
sheet.getRange("C:C"),
sheet.getRange("E:E")
].forEach(function (range) {
range
.setNumberFormat("hh:mm");
});
sheet.getRange("F:F")
.setNumberFormat("[h]:mm");
// set title
sheet.getRange("B2:G2")
.setDataValidation(null)
.setValues(new Array([
'start', '',
'stop', '',
'duration', 'task'
]));
// set width
sheet
.setColumnWidth(2, 150)
.setColumnWidth(4, 150)
.setColumnWidth(7, 200);
// set initial formula
sheet.getRange("F3")
.setValue(durationFormula(3));
}
function appendTaskTime(rowNumber, offset) {
var sheet = SpreadsheetApp
.getActiveSpreadsheet()
.getActiveSheet();
var now = new Date();
sheet.getRange(rowNumber, offset)
.setValue(now.toLocaleDateString());
sheet.getRange(rowNumber, offset + 1)
.setValue(now.getHours() + ":" + now.getMinutes());
}
function endTask() {
var sheet = SpreadsheetApp
.getActiveSpreadsheet()
.getActiveSheet();
var rowNo = sheet.getLastRow();
var value = sheet.getRange(rowNo, 4).getValue();
if (value !== "") {
return;
}
appendTaskTime(rowNo, 4);
sheet.getRange(rowNo, 6)
.setValue(durationFormula(rowNo));
}
function startTask() {
var sheet = SpreadsheetApp
.getActiveSpreadsheet()
.getActiveSheet();
var rowNo = sheet.getLastRow() + 1;
endTask();
appendTaskTime(rowNo, 2);
sheet
.setActiveRange(sheet.getRange(rowNo, 7));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment