fork download
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5.  
  6. public class Test
  7. {
  8. public static string GetReadableTimespan(TimeSpan ts)
  9. {
  10. const int SECOND = 1;
  11. const int MINUTE = 60 * SECOND;
  12. const int HOUR = 60 * MINUTE;
  13. const int DAY = 24 * HOUR;
  14. const int MONTH = 30 * DAY;
  15. double delta = Math.Abs(ts.TotalSeconds);
  16.  
  17. if (delta < 0)
  18. {
  19. return "not yet";
  20. }
  21. if (delta < 1 * MINUTE)
  22. {
  23. return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
  24. }
  25. if (delta < 2 * MINUTE)
  26. {
  27. return "a minute ago";
  28. }
  29. if (delta < 45 * MINUTE)
  30. {
  31. return ts.Minutes + " minutes ago";
  32. }
  33. if (delta < 90 * MINUTE)
  34. {
  35. return "an hour ago";
  36. }
  37. if (delta < 24 * HOUR)
  38. {
  39. return ts.Hours + " hours ago";
  40. }
  41. if (delta < 48 * HOUR)
  42. {
  43. return "yesterday";
  44. }
  45. if (delta < 30 * DAY)
  46. {
  47. return ts.Days + " days ago";
  48. }
  49. if (delta < 12 * MONTH)
  50. {
  51. int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  52. return months <= 1 ? "one month ago" : months + " months ago";
  53. }
  54. else
  55. {
  56. int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  57. return years <= 1 ? "one year ago" : years + " years ago";
  58. }
  59. }
  60.  
  61. public static void Main()
  62. {
  63. string[] strTimeSpans = new[]{"00hr:00min:17sec","00hr:03min:18sec","00hr:05min:25sec","01hr:39min:44sec"};
  64. TimeSpan[] timespans = strTimeSpans
  65. .Select(s => {
  66. var parts = s.Split(':');
  67. int hour = int.Parse(parts[0].Substring(0, 2));
  68. int min = int.Parse(parts[1].Substring(0, 2));
  69. int sec = int.Parse(parts[2].Substring(0, 2));
  70. return new TimeSpan(hour, min, sec);
  71. }).ToArray();
  72.  
  73. foreach (TimeSpan ts in timespans)
  74. Console.WriteLine(GetReadableTimespan(ts));
  75. }
  76. }
Success #stdin #stdout 0.04s 33856KB
stdin
Standard input is empty
stdout
17 seconds ago
3 minutes ago
5 minutes ago
1 hours ago