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

前端 未结 7 1042
余生分开走
余生分开走 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:12

    If anyone reads this far down in the post then here's another thought. As z666zz666z said, it doesn't have to be complicated. TDateTime in Delphi is a double precision floating point number with the integer portion representing the day. If the rounding value is passed as the number of 'periods' in the day then the rounding function would simply be: Round(dt * RoundingValue) / RoundingValue. The method would be:

    procedure RoundTo(var dt: TDateTime; RoundingValue:integer);
        begin
        if RoundingValue > 0 then
            dt := Round(dt * RoundingValue) / RoundingValue;
        end;
    

    Examples:

    RoundTo(targetDateTime, SecsPerDay); // round to the nearest second
    RoundTo(targetDateTime, SecsPerDay div 10); // round to the nearest 10 seconds
    RoundTo(targetDateTime, MinsPerDay); // round to the nearest minute
    RoundTo(targetDateTime, MinsPerDay div 5); // round to the nearest five minutes
    RoundTo(targetDateTime, HoursPerDay); // round to the nearest hour
    

    It even caters to sub second rounding:

    RoundTo(targetDateTime, SecsPerDay * 10); // round to the nearest 1/10 second
    

提交回复
热议问题