HumanReadHelper.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. namespace FNZCM.Shared.Helpers
  2. {
  3. public static class HumanReadHelper
  4. {
  5. public static string NullOrEmptyEscape(this string me, string escape) => string.IsNullOrWhiteSpace(me) ? escape : me;
  6. public static string SecondToDur(this int sec) => ((int?)sec).SecondToDur();
  7. public static string SecondToDur(this int? sec)
  8. {
  9. if (sec.HasValue == false) return string.Empty;
  10. var ts = TimeSpan.FromSeconds(sec.Value);
  11. return Math.Floor(ts.TotalDays) >= 1
  12. ? $"{Math.Floor(ts.TotalDays):00}.{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}"
  13. : Math.Floor(ts.TotalHours) >= 1
  14. ? $"{Math.Floor(ts.TotalHours):00}:{ts.Minutes:00}:{ts.Seconds:00}"
  15. : $"{Math.Floor(ts.TotalMinutes):00}:{ts.Seconds:00}";
  16. }
  17. public static string BytesToFileSize(this long length) => ((long?)length).BytesToFileSize();
  18. public static string BytesToFileSize(this long? length)
  19. {
  20. if (length.HasValue == false) return string.Empty;
  21. string[] sizes = { "B", "KB", "MB", "GB", "TB" };
  22. double len = length.Value;
  23. int order = 0;
  24. while (len >= 1024 && order < sizes.Length - 1)
  25. {
  26. order++;
  27. len = len / 1024;
  28. }
  29. // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
  30. // show a single decimal place, and no space.
  31. string result = $"{len:000.00}{sizes[order]}";
  32. return result;
  33. }
  34. }
  35. }