In Delphi: How do I round a TDateTime to closest second, minute, five-minute etc?

前端 未结 7 1078
余生分开走
余生分开走 2021-01-02 00:23

Does there exist a routine in Delphi that rounds a TDateTime value to the closest second, closest hour, closest 5-minute, closest half hour etc?

UPDATE:

Gab

7条回答
  •  自闭症患者
    2021-01-02 01:00

    Here is an untested code with adjustable precision.

    Type
      TTimeDef = (tdSeconds, tdMinutes, tdHours, tdDays)
    
    function ToClosest( input : TDateTime; TimeDef : TTimeDef ; Range : Integer ) : TDateTime
    var 
      Coeff : Double;
    RInteger : Integer;
    DRInteger : Integer;
    begin
      case TimeDef of
        tdSeconds :  Coeff := SecsPerDay;  
        tdMinutes : Coeff := MinsPerDay;
        tdHours : Coeff :=  MinsPerDay/60;
        tdDays : Coeff := 1;
      end;
    
      RInteger := Trunc(input * Coeff);
      DRInteger := RInteger div Range * Range
      result := DRInteger / Coeff;
      if (RInteger - DRInteger) >= (Range / 2) then
        result := result + Range / Coeff;
    
    end;
    

提交回复
热议问题