DateTimeExtension.cs 1.4 KB

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