Calculate relative time in C#

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

    Jeff, your code is nice but could be clearer with constants (as suggested in Code Complete).

    const int SECOND = 1;
    const int MINUTE = 60 * SECOND;
    const int HOUR = 60 * MINUTE;
    const int DAY = 24 * HOUR;
    const int MONTH = 30 * DAY;
    
    var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
    double delta = Math.Abs(ts.TotalSeconds);
    
    if (delta < 1 * MINUTE)
      return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
    
    if (delta < 2 * MINUTE)
      return "a minute ago";
    
    if (delta < 45 * MINUTE)
      return ts.Minutes + " minutes ago";
    
    if (delta < 90 * MINUTE)
      return "an hour ago";
    
    if (delta < 24 * HOUR)
      return ts.Hours + " hours ago";
    
    if (delta < 48 * HOUR)
      return "yesterday";
    
    if (delta < 30 * DAY)
      return ts.Days + " days ago";
    
    if (delta < 12 * MONTH)
    {
      int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
      return months <= 1 ? "one month ago" : months + " months ago";
    }
    else
    {
      int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
      return years <= 1 ? "one year ago" : years + " years ago";
    }
    
    0 讨论(0)
  • 2020-11-21 06:29

    If you want to have an output like "2 days, 4 hours and 12 minutes ago", you need a timespan:

    TimeSpan timeDiff = DateTime.Now-CreatedDate;
    

    Then you can access the values you like:

    timeDiff.Days
    timeDiff.Hours
    

    etc...

    0 讨论(0)
  • 2020-11-21 06:30
    /** 
     * {@code date1} has to be earlier than {@code date2}.
     */
    public static String relativize(Date date1, Date date2) {
        assert date2.getTime() >= date1.getTime();
    
        long duration = date2.getTime() - date1.getTime();
        long converted;
    
        if ((converted = TimeUnit.MILLISECONDS.toDays(duration)) > 0) {
            return String.format("%d %s ago", converted, converted == 1 ? "day" : "days");
        } else if ((converted = TimeUnit.MILLISECONDS.toHours(duration)) > 0) {
            return String.format("%d %s ago", converted, converted == 1 ? "hour" : "hours");
        } else if ((converted = TimeUnit.MILLISECONDS.toMinutes(duration)) > 0) {
            return String.format("%d %s ago", converted, converted == 1 ? "minute" : "minutes");
        } else if ((converted = TimeUnit.MILLISECONDS.toSeconds(duration)) > 0) {
            return String.format("%d %s ago", converted, converted == 1 ? "second" : "seconds");
        } else {
            return "just now";
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:31

    jquery.timeago plugin

    Jeff, because Stack Overflow uses jQuery extensively, I recommend the jquery.timeago plugin.

    Benefits:

    • Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.
    • You can take full advantage of page and/or fragment caching in your web applications, because the timestamps aren't calculated on the server.
    • You get to use microformats like the cool kids.

    Just attach it to your timestamps on DOM ready:

    jQuery(document).ready(function() {
        jQuery('abbr.timeago').timeago();
    });
    

    This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title:

    <abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>
    

    into something like this:

    <abbr class="timeago" title="July 17, 2008">4 months ago</abbr>
    

    which yields: 4 months ago. As time passes, the timestamps will automatically update.

    Disclaimer: I wrote this plugin, so I'm biased.

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

    using Fluent DateTime

    var dateTime1 = 2.Hours().Ago();
    var dateTime2 = 3.Days().Ago();
    var dateTime3 = 1.Months().Ago();
    var dateTime4 = 5.Hours().FromNow();
    var dateTime5 = 2.Weeks().FromNow();
    var dateTime6 = 40.Seconds().FromNow();
    
    0 讨论(0)
  • 2020-11-21 06:31

    @Jeff

    var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
    

    Doing a subtraction on DateTime returns a TimeSpan anyway.

    So you can just do

    (DateTime.UtcNow - dt).TotalSeconds
    

    I'm also surprised to see the constants multiplied-out by hand and then comments added with the multiplications in. Was that some misguided optimisation?

    0 讨论(0)
提交回复
热议问题