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

前端 未结 7 1077
余生分开走
余生分开走 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 00:59

    This is a very useful bit of code, I use this because I find the datetime tends to 'drift' if you increment it by hours or minutes many times over, which can mess things up if you're working to a strict time series. eg so 00:00:00.000 becomes 23:59:59.998 I implemented Sveins version of Gabrs code, but I suggest a few amendments: The default value didn't work for me, also the '(vTimeSec / SecsPerDay)' after the exit I think is a mistake, it shouldn't be there. My code with corrections & comments, is:

        Procedure TNumTool.RoundDateTimeToNearestInterval
                            (const ATime:TDateTime; AInterval:TDateTime{=5*60/SecsPerDay}; Var Result:TDateTime);
        var                                            //Rounds to nearest 5-minute by default
          vTimeSec,vIntSec,vRoundedSec : int64;     //NB datetime values are in days since 12/30/1899 as a double
        begin
          if AInterval = 0 then
            AInterval := 5*60/SecsPerDay;                 // no interval given - use default value of 5 minutes
          vTimeSec := round(ATime * SecsPerDay);          // input time in seconds as integer
          vIntSec  := round(AInterval * SecsPerDay);      // interval time in seconds as integer
          if vIntSec = 0 then
            exit;                                           // interval is zero -cannot round the datetime;
          vRoundedSec := round(vTimeSec / vIntSec) * vIntSec;   // rounded time in seconds as integer
          Result      := vRoundedSec / SecsPerDay;              // rounded time in days as tdatetime (double)
        end;
    

提交回复
热议问题