When dealing with time in Pascal, you calculate the amount of time between two different events. For example, you may want to check long it takes part of a program to run, or see how long someone has been logged in or to track the time during a multiple choice test. Once you collect two different times, you encode them into a numerical form, subtract and then display the time difference.
- Skill level:
Open your Pascal source file in a text editor such as Windows Notepad.
Type the following code at the top of your file:
Using "Dos" provides access to the "GetTime" function. Using "sysutils" provides access to the "EncodeTime" and "DecodeTime" functions.
Declare variables that will store the time values by adding the code:
Hour 1, Min 1, Sec 1, HSec1 : word;
Hour 2, Min 2, Sec 2, HSec2 : word;
Hour 3, Min 3, Sec 3, MSec3 : word;
x, y, z : TDateTime;
Get the first time at the beginning of your function by adding the code:
GetTime(Hour 1, Min 1, Sec 1, HSec1);
Perform the main code of your function and then call "GetTime" again by adding the code:
GetTime(Hour 2, Min 2, Sec 2, HSec2);
Compute the difference between the two times by adding the code:
x := EncodeTime(Hour 1, Min 1, Sec 1, 0);
y := EncodeTime(Hour 2, Min 2, Sec 2, 0);
z := y - x;
DecodeTime(z, Hour 3, Min 3, Sec 3, MSec3);
The "EncodeTime" function converts the time into a "TDateTime" value, which is stored as a "double." The code subtracts the two times and then decodes the result into a printable format.
Display the time difference with the "writeln" function by adding the code:
Writeln (format('Time difference = %d:%d:%d',[Hour3,Min 3,Sec 3]));
Save your file, compile and run the program to view the time measurements.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for