code_junkie

Converting Days into Human Readable Duration Text

Nov 12th, 2011
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. let divmod n m = n / m, n % m
  2.  
  3. let units = [
  4. ("Centuries", TimeSpan.TicksPerDay * 365L * 100L );
  5. ("Years", TimeSpan.TicksPerDay * 365L);
  6. ("Weeks", TimeSpan.TicksPerDay * 7L);
  7. ("Days", TimeSpan.TicksPerDay)
  8. ]
  9.  
  10. let duration days =
  11. let rec duration' ticks units acc =
  12. match units with
  13. | [] -> acc
  14. | (u::us) ->
  15. let (wholeUnits, ticksRemaining) = divmod ticks (snd u)
  16. duration' ticksRemaining us (((fst u), wholeUnits) :: acc)
  17. duration' (TimeSpan.FromDays(float days).Ticks) units []
  18.  
  19. String.Format("{0} Weeks, {1} days", days / 7, days % 7);
  20.  
  21. public class UnitOfMeasure {
  22. public UnitOfMeasure(string name, int value) {
  23. Name = name;
  24. Value = value;
  25. }
  26.  
  27. public string Name { get; set; }
  28. public int Value { get; set; }
  29.  
  30. public static UnitOfMeasure[] All = new UnitOfMeasure[] {
  31. new UnitOfMeasure("Year", 356),
  32. new UnitOfMeasure("Month", 30),
  33. new UnitOfMeasure("Week", 7),
  34. new UnitOfMeasure("Day", 1)
  35. };
  36.  
  37. public static string ConvertToDuration(int days) {
  38. List<string> results = new List<string>();
  39.  
  40. for (int i = 0; i < All.Length; i++) {
  41. int count = days / All[i].Value;
  42.  
  43. if (count >= 1) {
  44. results.Add((count + " " + All[i].Name) + (count == 1 ? string.Empty : "s"));
  45. days -= count * All[i].Value;
  46. }
  47. }
  48.  
  49. return string.Join(", ", results.ToArray());
  50. }
  51. }
  52.  
  53. #light
  54. let conversions = [|
  55. 365, "Year", "Years"
  56. 30, "Month", "Months"
  57. 7, "Week", "Weeks"
  58. 1, "Day", "Days" |]
  59. let ToDuration numDays =
  60. conversions
  61. |> Array.fold_left (fun (remainDays,results) (n,sing,plur) ->
  62. let count = remainDays / n
  63. if count >= 1 then
  64. remainDays - (count * n),
  65. (sprintf "%d %s" count (if count=1 then sing else plur)) :: results
  66. else
  67. remainDays, results
  68. ) (numDays,[])
  69. |> snd |> (fun rs -> System.String.Join(", ", List.rev rs |> List.to_array))
  70. printfn "%s" (ToDuration 1008)
Add Comment
Please, Sign In to add comment