胡子哥哥
估计这道题不让用DateTime的相关函数,否则太简单了。 下面的例子,从校验用户的输入,直到计算时间差,都是用系统的其他函数(非datetime相关),有效时间的范围是:00:00:00~24:00:00 ,可以个位输出,例: 0:1:2. --- 为了对比,给出了使用TDateTime相关函数及不使用的方法。program time_difference;uses strutils, sysutils;type //方法一: 使用TDateTime function getTimeDiff(const stime1 : string; const stime2 : string; var sdiff: string) : Boolean; var dt1, dt2, dtdiff: TDateTime; begin try dt1 := StrToDateTime(stime1); dt2 := StrToDateTime(stime2); dtdiff := dt1 - dt2; DateTimeToString(sdiff, 'hh:mm:ss', dtdiff); except on E:EConvertError do exit(false); end; getTimeDiff := true; end; //方法二: 不使用TDateTime function getTimeDiff_2(const stime1 : string; const stime2 : string; var sdiff: string) : Boolean; var time_1, time_2, time_diff : longint; t_hour, t_minute, t_second : longint; begin if not getTimeInSeconds(stime1, time_1) then exit(false); if not getTimeInSeconds(stime2, time_2) then exit(false); time_diff := time_1 - time_2; if time_diff < 0 then time_diff := -time_diff; t_hour := time_diff div 3600; t_minute := time_diff mod 3600 div 60; t_second := time_diff - t_hour * 3600 - t_minute * 60; sdiff := Format('%.2d:%.2d:%.2d', [t_hour, t_minute, t_second]); exit(true); end; //方法二用到的函数 function getTimeInSeconds(const stime : string; var time_in_seconds : longint) : Boolean; var s_hh, s_mm, s_ss : string; hour, minute, second, errcode : integer; begin s_hh := ExtractDelimited(1, stime, [':']); s_mm := ExtractDelimited(2, stime, [':']); s_ss := ExtractDelimited(3, stime, [':']); Val(s_hh, hour, errcode); if errcode <> 0 then exit(false); Val(s_mm, minute, errcode); if errcode <> 0 then exit(false); Val(s_ss, second, errcode); if errcode <> 0 then exit(false); if not (hour in [0..24]) then exit (false); if not (minute in [0..59]) then exit (false); if not (second in [0..59]) then exit (false); if (hour = 24) and ( (minute <> 0) or (second <> 0) ) then exit(false); time_in_seconds := hour * 3600 + minute * 60 + second; exit(true); end;//主程序var stime1, stime2 : String; //t_sec_1, t_sec_2 : Longint; stdiff : string;begin writeln ('Input two times (hh:mm:ss):'); readln(stime1); readln(stime2); //方法一 if getTimeDiff(stime1, stime2, stdiff) then writeln(stdiff) else writeln('Error happened.'); //方法二 if getTimeDiff_2(stime1, stime2, stdiff) then writeln('Diff. ', stdiff) else writeln('Error happened.'); end.运行:Input two times (hh:mm:ss):12:34:5623:45:001. 11:10:042. 11:10:04