Calculate relative time in C#

后端 未结 30 2116
生来不讨喜
生来不讨喜 2020-11-21 05:59

Given a specific DateTime value, how do I display relative time, like:

  • 2 hours ago
  • 3 days ago
  • a month ago
30条回答
  •  野性不改
    2020-11-21 06:10

    Here's the algorithm stackoverflow uses but rewritten more concisely in perlish pseudocode with a bug fix (no "one hours ago"). The function takes a (positive) number of seconds ago and returns a human-friendly string like "3 hours ago" or "yesterday".

    agoify($delta)
      local($y, $mo, $d, $h, $m, $s);
      $s = floor($delta);
      if($s<=1)            return "a second ago";
      if($s<60)            return "$s seconds ago";
      $m = floor($s/60);
      if($m==1)            return "a minute ago";
      if($m<45)            return "$m minutes ago";
      $h = floor($m/60);
      if($h==1)            return "an hour ago";
      if($h<24)            return "$h hours ago";
      $d = floor($h/24);
      if($d<2)             return "yesterday";
      if($d<30)            return "$d days ago";
      $mo = floor($d/30);
      if($mo<=1)           return "a month ago";
      $y = floor($mo/12);
      if($y<1)             return "$mo months ago";
      if($y==1)            return "a year ago";
      return "$y years ago";
    

提交回复
热议问题