Calculate relative time in C#

后端 未结 30 2181
生来不讨喜
生来不讨喜 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:11

    Is there an easy way to do this in Java? The java.util.Date class seems rather limited.

    Here is my quick and dirty Java solution:

    import java.util.Date;
    import javax.management.timer.Timer;
    
    String getRelativeDate(Date date) {     
      long delta = new Date().getTime() - date.getTime();
      if (delta < 1L * Timer.ONE_MINUTE) {
        return toSeconds(delta) == 1 ? "one second ago" : toSeconds(delta) + " seconds ago";
      }
      if (delta < 2L * Timer.ONE_MINUTE) {
        return "a minute ago";
      }
      if (delta < 45L * Timer.ONE_MINUTE) {
        return toMinutes(delta) + " minutes ago";
      }
      if (delta < 90L * Timer.ONE_MINUTE) {
        return "an hour ago";
      }
      if (delta < 24L * Timer.ONE_HOUR) {
        return toHours(delta) + " hours ago";
      }
      if (delta < 48L * Timer.ONE_HOUR) {
        return "yesterday";
      }
      if (delta < 30L * Timer.ONE_DAY) {
        return toDays(delta) + " days ago";
      }
      if (delta < 12L * 4L * Timer.ONE_WEEK) { // a month
        long months = toMonths(delta); 
        return months <= 1 ? "one month ago" : months + " months ago";
      }
      else {
        long years = toYears(delta);
        return years <= 1 ? "one year ago" : years + " years ago";
      }
    }
    
    private long toSeconds(long date) {
      return date / 1000L;
    }
    
    private long toMinutes(long date) {
      return toSeconds(date) / 60L;
    }
    
    private long toHours(long date) {
      return toMinutes(date) / 60L;
    }
    
    private long toDays(long date) {
      return toHours(date) / 24L;
    }
    
    private long toMonths(long date) {
      return toDays(date) / 30L;
    }
    
    private long toYears(long date) {
      return toMonths(date) / 365L;
    }
    
    0 讨论(0)
  • 2020-11-21 06:12

    Here a rewrite from Jeffs Script for PHP:

    define("SECOND", 1);
    define("MINUTE", 60 * SECOND);
    define("HOUR", 60 * MINUTE);
    define("DAY", 24 * HOUR);
    define("MONTH", 30 * DAY);
    function relativeTime($time)
    {   
        $delta = time() - $time;
    
        if ($delta < 1 * MINUTE)
        {
            return $delta == 1 ? "one second ago" : $delta . " seconds ago";
        }
        if ($delta < 2 * MINUTE)
        {
          return "a minute ago";
        }
        if ($delta < 45 * MINUTE)
        {
            return floor($delta / MINUTE) . " minutes ago";
        }
        if ($delta < 90 * MINUTE)
        {
          return "an hour ago";
        }
        if ($delta < 24 * HOUR)
        {
          return floor($delta / HOUR) . " hours ago";
        }
        if ($delta < 48 * HOUR)
        {
          return "yesterday";
        }
        if ($delta < 30 * DAY)
        {
            return floor($delta / DAY) . " days ago";
        }
        if ($delta < 12 * MONTH)
        {
          $months = floor($delta / DAY / 30);
          return $months <= 1 ? "one month ago" : $months . " months ago";
        }
        else
        {
            $years = floor($delta / DAY / 365);
            return $years <= 1 ? "one year ago" : $years . " years ago";
        }
    }    
    
    0 讨论(0)
  • 2020-11-21 06:13

    I got this answer from one of Bill Gates' blogs. I need to find it on my browser history and I'll give you the link.

    The Javascript code to do the same thing (as requested):

    function posted(t) {
        var now = new Date();
        var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);
        if (diff < 60) { return 'less than a minute ago'; }
        else if (diff < 120) { return 'about a minute ago'; }
        else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }
        else if (diff < (5400)) { return 'about an hour ago'; }
        else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }
        else if (diff < (172800)) { return '1 day ago'; } 
        else {return (parseInt(diff / 86400)).toString() + ' days ago'; }
    }
    

    Basically, you work in terms of seconds.

    0 讨论(0)
  • 2020-11-21 06:16

    There are also a package called Humanizr on Nuget, and it actually works really well, and is in the .NET Foundation.

    DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday"
    DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago"
    
    DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
    DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"
    
    TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
    TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"
    

    Scott Hanselman has a writeup on it on his blog

    0 讨论(0)
  • 2020-11-21 06:17

    @jeff

    IMHO yours seems a little long. However it does seem a little more robust with support for "yesterday" and "years". But in my experience when this is used, the person is most likely to view the content in the first 30 days. It is only the really hardcore people that come after that. So, I usually elect to keep this short and simple.

    This is the method I am currently using in one of my websites. This returns only a relative day, hour and time. And then the user has to slap on "ago" in the output.

    public static string ToLongString(this TimeSpan time)
    {
        string output = String.Empty;
    
        if (time.Days > 0)
            output += time.Days + " days ";
    
        if ((time.Days == 0 || time.Days == 1) && time.Hours > 0)
            output += time.Hours + " hr ";
    
        if (time.Days == 0 && time.Minutes > 0)
            output += time.Minutes + " min ";
    
        if (output.Length == 0)
            output += time.Seconds + " sec";
    
        return output.Trim();
    }
    
    0 讨论(0)
  • 2020-11-21 06:17

    In PHP, I do it this way:

    <?php
    function timesince($original) {
        // array of time period chunks
        $chunks = array(
            array(60 * 60 * 24 * 365 , 'year'),
            array(60 * 60 * 24 * 30 , 'month'),
            array(60 * 60 * 24 * 7, 'week'),
            array(60 * 60 * 24 , 'day'),
            array(60 * 60 , 'hour'),
            array(60 , 'minute'),
        );
    
        $today = time(); /* Current unix time  */
        $since = $today - $original;
    
        if($since > 604800) {
        $print = date("M jS", $original);
    
        if($since > 31536000) {
            $print .= ", " . date("Y", $original);
        }
    
        return $print;
    }
    
    // $j saves performing the count function each time around the loop
    for ($i = 0, $j = count($chunks); $i < $j; $i++) {
    
        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];
    
        // finding the biggest chunk (if the chunk fits, break)
        if (($count = floor($since / $seconds)) != 0) {
            break;
        }
    }
    
    $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
    
    return $print . " ago";
    
    } ?>
    
    0 讨论(0)
提交回复
热议问题