top of page

99. Parsing Time Values

Description

Parse hours, minutes, and am/pm from a text string and SET them in number variables for time calculations

Code

// First the hours
SET Hour-n TO INTEGER( TextVar )

// Change hours to military time
IF TextVar CONTAINS "am"
OR TextVar CONTAINS "a.m."
IF Hour-n = 12
SET Hour-n TO 0
END IF
ELSE IF TextVar CONTAINS "pm"
OR TextVar CONTAINS "p.m."
IF Hour-n < 12
SET Hour-n TO Hour-n + 12
END IF
END IF

// Minutes
SET Temp-n TO POSITION( TextVar, ":" )
IF Temp-n > 0
SET Min-n TO INTEGER( LAST( TextVar, LENGTH( TextVar ) - Temp-n ))
ELSE
SET Min-n TO 0
END IF

Explanation

Before you can do time calculations, you must get the hours and minutes into separate number variables. Ideally you would have the user input these values directly into number variables, but it may be that the time value is in a text variable. This computation will extract a time value from a text variable and place the hours (as military time) and minutes into number variables. This computation assumes that the time is in the format Hours:Minutes am/pm, with no other text in the string. Leading zeros are not necessary (i.e. both 02:00 and 2:00 are fine).

Variables: The computation assumes the following variables:

• TextVar - The text variable containing the time value.
• Hour-n - A number variable which will be set to the hours value.
• Min-n - A number variable which will be set to the minutes value.
• Temp-n - A temporary number variable.

Hours: Assuming that the first item in the string is the hours value, we can extract it by simply using the INTEGER model, which takes every character up to the first non-numeric character and converts it to an integer value. We then place this value in our Hour-n variable.

AM/PM: The easiest way to deal with am/pm in time computations is to simply make sure that the hours are in military time (00:00 for 12:00 am, 13:00 for 1:00 pm, 23:00 for 11:00 pm). The quickest way to find whether the time in TextVar is am or pm is to use the CONTAINS model, which looks to see if a string contains a given character or short string. TextVar CONTAINS "pm" will quickly tell us whether the time value in TextVar is am or pm. If the time is am and the hour is 12, we will need to change the Hour-n variable to 0. If the time is pm and the hour is 1-11, we will need to add 12 hours to the Hour-n variable.

Minutes: To extract the minutes from the time value, we first need to find the position of the colon ":" in the time string. We set this position in the temporary number variable Temp-n for easy reference. Once we know where the colon is, we can again use the INTEGER model to extract the integer value of everything after the colon. This value is then placed in the Min-n variable.

Time Calculations: With the hours and minutes now placed in the Hour-n and Min-n variables, you can do time calculations such as Computation #0100: Elapsed Time, and Computation #0101: Total Time.

bottom of page