Posted By

icebob on 08/02/10


Tagged


Versions (?)

Convert seconds to string ( like '4h 13m' )


 / Published in: Delphi
 

SecondsToTimeString(Seconds: Int64): string; Convert a seconds integer to time string like: '4m 35s' or '2 month 21 day'

  1. function SecondsToTimeString(Seconds: Int64): string;
  2. const
  3. itemNames: TTimeItemNames = ('year', 'month', 'day', 'h', 'm', 's');
  4. begin
  5. result := SecondsToTimeString(Seconds, itemNames);
  6. end;
  7.  
  8. function SecondsToTimeString(Seconds: Int64; const itemNames: TTimeItemNames): string;
  9. const
  10. divisors: array [0..5] of Int64 = (SecsPerDay * 365, SecsPerDay * 31, SecsPerDay, SecsPerHour, SecsPerMin, 1);
  11.  
  12. var
  13. resCount: integer;
  14. I: Integer;
  15. C, V: Int64;
  16. begin
  17. result := '';
  18. resCount := 0;
  19. C := Seconds;
  20. for I := Low(divisors) to High(divisors) do
  21. begin
  22. V := C div divisors[I];
  23. if V > 0 then
  24. begin
  25. if resCount > 0 then
  26. result := result + ' ';
  27. result := result + IntToStr(V) + itemNames[I];
  28. Inc(resCount);
  29. if resCount > 1 then break;
  30. C := C mod divisors[I];
  31. end;
  32. end;
  33. end;

Report this snippet  

You need to login to post a comment.