How to convert hh:mm:ss to minutes in Pascal

1 Answer

0 votes
program TimeConverter; 

uses
  SysUtils; 

function TimeToMinutesWithSecondsFraction(const TimeStr: string): string;
var
  Hours, Minutes, Seconds: Integer;
  TotalMinutes: Real;
  i: Integer;
begin
  // Initialize result to an empty string in case of errors
  TimeToMinutesWithSecondsFraction := '';

  // Check if the input string has the correct format (hh:mm:ss)
  if Length(TimeStr) <> 8 then
    Exit;

  // Parse the hours
  Val(Copy(TimeStr, 1, 2), Hours, i);
  if i <> 0 then
    Exit; // Invalid hours

  // Check for the first colon
  if TimeStr[3] <> ':' then
    Exit;

  // Parse the minutes
  Val(Copy(TimeStr, 4, 2), Minutes, i);
  if i <> 0 then
    Exit; // Invalid minutes

  // Check for the second colon
  if TimeStr[6] <> ':' then
    Exit;

  // Parse the seconds
  Val(Copy(TimeStr, 7, 2), Seconds, i);
  if i <> 0 then
    Exit; // Invalid seconds

  // Check if the values are within valid ranges
  if (Hours < 0) or (Hours > 23) or
     (Minutes < 0) or (Minutes > 59) or
     (Seconds < 0) or (Seconds > 59) then
    Exit; // Invalid time values

  // Calculate the total minutes with the fraction of seconds
  TotalMinutes := (Hours * 60) + Minutes + (Seconds / 60.0);

  // Format the Real number to a string with two decimal places
  TimeToMinutesWithSecondsFraction := FormatFloat('0.00', TotalMinutes); // Direct assignment
end;

var
  TimeString: string;
  FormattedMinutes: string;
  TotalMinutes: string;

begin
  TimeString := '02:30:00';
  TotalMinutes := TimeToMinutesWithSecondsFraction(TimeString);

  Writeln('The time ', TimeString, ' is equal to ', TotalMinutes, ' minutes.');

  TimeString := '02:35:30';
  TotalMinutes := TimeToMinutesWithSecondsFraction(TimeString);

  Writeln('The time ', TimeString, ' is equal to ', TotalMinutes, ' minutes.');

  TimeString := '05:00:45'; 
  TotalMinutes := TimeToMinutesWithSecondsFraction(TimeString);

  Writeln('The time ', TimeString, ' is equal to ', TotalMinutes, ' minutes.');
end.


(*
run:

The time 02:30:00 is equal to 150.00 minutes.
The time 02:35:30 is equal to 155.50 minutes.
The time 05:00:45 is equal to 300.75 minutes.

*)

 



answered Apr 17, 2025 by avibootz

Related questions

1 answer 94 views
1 answer 90 views
1 answer 115 views
1 answer 98 views
1 answer 113 views
1 answer 103 views
1 answer 184 views
...