DateTimeExtension.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. namespace wispro.sp.web
  3. {
  4. public static class DateTimeExtension
  5. {
  6. private const int Second = 1;
  7. private const int Minute = 60 * Second;
  8. private const int Hour = 60 * Minute;
  9. private const int Day = 24 * Hour;
  10. private const int Month = 30 * Day;
  11. // todo: Need to be localized
  12. public static string ToFriendlyDisplay(this DateTime dateTime)
  13. {
  14. var ts = DateTime.Now - dateTime;
  15. var delta = ts.TotalSeconds;
  16. if (delta < 0)
  17. {
  18. return "not yet";
  19. }
  20. if (delta < 1 * Minute)
  21. {
  22. return ts.Seconds == 1 ? "1 秒前" : ts.Seconds + " 秒前";
  23. }
  24. if (delta < 2 * Minute)
  25. {
  26. return "1 分钟前";
  27. }
  28. if (delta < 45 * Minute)
  29. {
  30. return ts.Minutes + "分钟";
  31. }
  32. if (delta < 90 * Minute)
  33. {
  34. return "1 小说前";
  35. }
  36. if (delta < 24 * Hour)
  37. {
  38. return ts.Hours + "小时前";
  39. }
  40. if (delta < 48 * Hour)
  41. {
  42. return "昨天";
  43. }
  44. if (delta < 30 * Day)
  45. {
  46. return ts.Days + "天前";
  47. }
  48. if (delta < 12 * Month)
  49. {
  50. var months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  51. return months <= 1 ? "一月前" : months + "月前";
  52. }
  53. else
  54. {
  55. var years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  56. return years <= 1 ? "一年前" : years + "年前";
  57. }
  58. }
  59. }
  60. }