Created
January 15, 2020 19:26
-
-
Save mike-pete/dfec0d604c1b3fcc497dcf0da74b5cde to your computer and use it in GitHub Desktop.
This file contains 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
/* This script: | |
* - takes 2 time entries [(hh:mm) (AM or PM)] and [(hh:mm) (AM or PM)] | |
* - calculates the time difference between them | |
* - saves the time difference in the Total Time field | |
* | |
* This script requires the following fields: | |
* - 2 text entry fields ("Start Time" and "End Time") | |
* - 2 dropdowns ("Start AM or PM" and "End AM or PM") these have the options "AM" and "PM" respectively | |
* - 1 read only text entry field (Total Time) | |
*/ | |
// simple function to throw exeption | |
def err(String toSay){throw new RuntimeException(toSay);} | |
// timeToDecimal("11:30") > 11.5 | |
double timeToDecimal(String time){ | |
String [] timeSplit = time.split(':'); // split into hrs and min | |
double hrs, min; | |
// ensure minutes has two characters | |
if (timeSplit[1].length() != 2){err("Please enter time as: hh:mm");} | |
// convert split string to two doubles: "11:30" -> 11, 30 | |
try { | |
hrs = timeSplit[0] as double; | |
min = timeSplit[1] as double; | |
} | |
catch(Exception e){ | |
err("Please enter time as: hh:mm"); | |
} | |
// ensure hrs <= 12 and min <= 60 | |
if (hrs > 12 || hrs < 0 || min > 60 || min < 0){err("Invalid time entered!");} | |
hrs = (hrs == 12.0) ? 0 : hrs; | |
min = min / 60.0; // min -> decimal | |
return hrs + min; | |
} | |
String toggle1 = currentValues["Start AM or PM"]; | |
String toggle2 = currentValues["End AM or PM"]; | |
String time1 = currentValues["Start Time"].toString(); | |
String time2 = currentValues["End Time"].toString(); | |
double start = timeToDecimal(time1); | |
double end = timeToDecimal(time2); | |
double h, m; | |
// no time travel allowed | |
if (toggle1 == toggle2 && start >= end){ | |
err("End time must come after the Start time."); | |
} | |
// determine total time worked | |
h = (toggle1 == toggle2) | |
? end-start | |
: (end+12)-start; | |
// convert from decimal to min | |
m = (h%1)*60; | |
m = m.round(0); | |
// format the Total Time value | |
String totalHrs = (m < 10) | |
? (int)h + ":0" + (int)m | |
: (int)h + ":" + (int)m; | |
currentValues["Total Time"] = totalHrs; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment