fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. public static class TimeSpanExtensions
  6. {
  7. public static string FromNowFormatted(this DateTime date)
  8. {
  9. var sb = new StringBuilder();
  10.  
  11. var t = DateTime.Now - date;
  12.  
  13. var dic = new Dictionary<string, int>
  14. {
  15. {"years", (int)(t.Days / 365)},
  16. {"months", (int)(t.Days / 12)},
  17. {"days", t.Days},
  18. {"hours", t.Hours},
  19. {"minutes", t.Minutes},
  20. {"seconds", t.Seconds},
  21. };
  22.  
  23. bool b = false;
  24. foreach (var e in dic)
  25. {
  26. if (e.Value > 0 || b)
  27. {
  28. var v = e.Value;
  29. var k = v == 1 ? e.Key.TrimEnd('s') : e.Key ;
  30.  
  31. sb.Append(v + " " + k + "\n");
  32. b = true;
  33. }
  34. }
  35.  
  36. return sb.ToString();
  37. }
  38. }
  39.  
  40. public class Test
  41. {
  42. public static void Main()
  43. {
  44. var d1 = new DateTime(2013,1,1,0,0,1);
  45.  
  46. Console.WriteLine(d1.FromNowFormatted());
  47. }
  48. }
Success #stdin #stdout 0.04s 34808KB
stdin
Standard input is empty
stdout
13 months
158 days
21 hours
38 minutes
35 seconds