2
0

LastSeenTextConverter.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using MediaBrowser.Model.DTO;
  2. using System;
  3. using System.Globalization;
  4. using System.Windows.Data;
  5. namespace MediaBrowser.UI.Converters
  6. {
  7. public class LastSeenTextConverter : IValueConverter
  8. {
  9. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  10. {
  11. var user = value as DtoUser;
  12. if (user != null)
  13. {
  14. if (user.LastActivityDate.HasValue)
  15. {
  16. DateTime date = user.LastActivityDate.Value.ToLocalTime();
  17. return "Last seen " + GetRelativeTimeText(date);
  18. }
  19. }
  20. return null;
  21. }
  22. private static string GetRelativeTimeText(DateTime date)
  23. {
  24. TimeSpan ts = DateTime.Now - date;
  25. const int second = 1;
  26. const int minute = 60 * second;
  27. const int hour = 60 * minute;
  28. const int day = 24 * hour;
  29. const int month = 30 * day;
  30. int delta = System.Convert.ToInt32(ts.TotalSeconds);
  31. if (delta < 0)
  32. {
  33. return "not yet";
  34. }
  35. if (delta < 1 * minute)
  36. {
  37. return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
  38. }
  39. if (delta < 2 * minute)
  40. {
  41. return "a minute ago";
  42. }
  43. if (delta < 45 * minute)
  44. {
  45. return ts.Minutes + " minutes ago";
  46. }
  47. if (delta < 90 * minute)
  48. {
  49. return "an hour ago";
  50. }
  51. if (delta < 24 * hour)
  52. {
  53. return ts.Hours + " hours ago";
  54. }
  55. if (delta < 48 * hour)
  56. {
  57. return "yesterday";
  58. }
  59. if (delta < 30 * day)
  60. {
  61. return ts.Days + " days ago";
  62. }
  63. if (delta < 12 * month)
  64. {
  65. int months = System.Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  66. return months <= 1 ? "one month ago" : months + " months ago";
  67. }
  68. int years = System.Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  69. return years <= 1 ? "one year ago" : years + " years ago";
  70. }
  71. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  72. {
  73. throw new NotImplementedException();
  74. }
  75. }
  76. }