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


/ Published in: Delphi
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.