天天看点

用D制作计时器,原理,三位数减三位数。

1、变量声明:

var

 h1,m1,s1,h2,m2,s2,h3,m3,s3:integer;

  time1,time2:string;

  ptime1,ptime2:pchar;

  timelist1,timelist2:tStringList;

2、在计时开始按钮单击事件中,获得当前时间,并分割出时、分、秒。

  time1:=timetostr(time);                              //获得第一个当前时间,并且赋值给time1变量

  ptime1:=pchar(time1);                                    //把time1的字符串以pchar形式赋值给ptime1

  timelist1:=TStringList.Create;                       //建立一个字符串列表。         

  ExtractStrings([':'], [' '], ptime1, timelist1);       //分割获得的时间钟的时、分、秒

  h1:=strtoint(timelist1[0]);                                 //把时赋值给h1

  m1:=strtoint(timelist1[1]);                               //把分赋值给m1

  s1:=strtoint(timelist1[2]);                            //把秒赋值给s1

    timer1.Interval:=1000;     //设置timer周期为1000(一秒钟触发一次,设计时,timer的周期为0)

procedure Tstudyfrm.Timer1Timer(Sender: TObject);

begin

 time2:=timetostr(time);                                               //获得下一个个当前时间       

 ptime2:=pchar(time2);                                        

  timelist2:=TStringList.Create;

  ExtractStrings([':'], [' '], ptime2, timelist2);                   //分割

  h2:=strtoint(timelist2[0]);                                           //赋值

  m2:=strtoint(timelist2[1]);

  s2:=strtoint(timelist2[2]);

 if s2>=s1 then  //秒够减                                               //开始计算。。。。

 begin

 s3:=s2-s1;

   if m2>=m1 then  //分够减

     begin

       m3:=m2-m1;

         if h2>=h1 then  //时够减

         begin

           h3:=h2-h1;

         end

         else              //时不够减

         begin

           h3:=h2+24-h1;

         end;

 end

 else            //分不够减

 begin

      m3:=m2+60-m1;

      if h2>0 then

      begin

         h2:=h2-1;

     if h2>=h1 then  h3:=h2-h1 else h3:=h2+24-h1;

      end

      else

      begin

        h3:=h2+23-h1;

      end;

 end;

 end

 else        //秒不够减

 begin

    s3:=s2+60-s1;

      if m2>0 then

      begin

       m2:=m2-1;

          if m2>=m1 then

          begin

          m3:=m2-m1;

            if h2>=h1 then  h3:=h2-h1 else h3:=h2+24-h1;

          end

          else

          begin

             m3:=m2+60-m1;

               if h2>0 then

              begin

               h2:=h2-1;

                if h2>=h1 then  h3:=h2-h1 else h3:=h2+24-h1;

                  end

                else

                    begin

                    h3:=23-h1;

                   end;

          end;

      end

      else

      begin

          m3:=59-m1;

            if h2>0 then

            begin

            h2:=h2-1;

               if h2>=h1 then h3:=h2-h1 else

               begin

                 h3:=h2+24-h1;

               end;

            end

            else

            begin

               h3:=23-h1;

            end;

      end;

 end;

label3.Caption:=inttostr(h3)+'时'+inttostr(m3)+'分'+inttostr(s3)+'秒';        //用label控件显示时间。

end;