Calculate relative time in C#

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

    When you know the viewer's time zone, it might be clearer to use calendar days at the day scale. I'm not familiar with the .NET libraries so I don't know how you'd do that in C#, unfortunately.

    On consumer sites, you could also be hand-wavier under a minute. "Less than a minute ago" or "just now" could be good enough.

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

    You can reduce the server-side load by performing this logic client-side. View source on some Digg pages for reference. They have the server emit an epoch time value that gets processed by Javascript. This way you don't need to manage the end user's time zone. The new server-side code would be something like:

    public string GetRelativeTime(DateTime timeStamp)
    {
        return string.Format("<script>printdate({0});</script>", timeStamp.ToFileTimeUtc());
    }
    

    You could even add a NOSCRIPT block there and just perform a ToString().

    0 讨论(0)
  • 2020-11-21 06:09
    public static string RelativeDate(DateTime theDate)
    {
        Dictionary<long, string> thresholds = new Dictionary<long, string>();
        int minute = 60;
        int hour = 60 * minute;
        int day = 24 * hour;
        thresholds.Add(60, "{0} seconds ago");
        thresholds.Add(minute * 2, "a minute ago");
        thresholds.Add(45 * minute, "{0} minutes ago");
        thresholds.Add(120 * minute, "an hour ago");
        thresholds.Add(day, "{0} hours ago");
        thresholds.Add(day * 2, "yesterday");
        thresholds.Add(day * 30, "{0} days ago");
        thresholds.Add(day * 365, "{0} months ago");
        thresholds.Add(long.MaxValue, "{0} years ago");
        long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000;
        foreach (long threshold in thresholds.Keys) 
        {
            if (since < threshold) 
            {
                TimeSpan t = new TimeSpan((DateTime.Now.Ticks - theDate.Ticks));
                return string.Format(thresholds[threshold], (t.Days > 365 ? t.Days / 365 : (t.Days > 0 ? t.Days : (t.Hours > 0 ? t.Hours : (t.Minutes > 0 ? t.Minutes : (t.Seconds > 0 ? t.Seconds : 0))))).ToString());
            }
        }
        return "";
    }
    

    I prefer this version for its conciseness, and ability to add in new tick points. This could be encapsulated with a Latest() extension to Timespan instead of that long 1 liner, but for the sake of brevity in posting, this will do. This fixes the an hour ago, 1 hours ago, by providing an hour until 2 hours have elapsed

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

    Here's an implementation I added as an extension method to the DateTime class that handles both future and past dates and provides an approximation option that allows you to specify the level of detail you're looking for ("3 hour ago" vs "3 hours, 23 minutes, 12 seconds ago"):

    using System.Text;
    
    /// <summary>
    /// Compares a supplied date to the current date and generates a friendly English 
    /// comparison ("5 days ago", "5 days from now")
    /// </summary>
    /// <param name="date">The date to convert</param>
    /// <param name="approximate">When off, calculate timespan down to the second.
    /// When on, approximate to the largest round unit of time.</param>
    /// <returns></returns>
    public static string ToRelativeDateString(this DateTime value, bool approximate)
    {
        StringBuilder sb = new StringBuilder();
    
        string suffix = (value > DateTime.Now) ? " from now" : " ago";
    
        TimeSpan timeSpan = new TimeSpan(Math.Abs(DateTime.Now.Subtract(value).Ticks));
    
        if (timeSpan.Days > 0)
        {
            sb.AppendFormat("{0} {1}", timeSpan.Days,
              (timeSpan.Days > 1) ? "days" : "day");
            if (approximate) return sb.ToString() + suffix;
        }
        if (timeSpan.Hours > 0)
        {
            sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty,
              timeSpan.Hours, (timeSpan.Hours > 1) ? "hours" : "hour");
            if (approximate) return sb.ToString() + suffix;
        }
        if (timeSpan.Minutes > 0)
        {
            sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty, 
              timeSpan.Minutes, (timeSpan.Minutes > 1) ? "minutes" : "minute");
            if (approximate) return sb.ToString() + suffix;
        }
        if (timeSpan.Seconds > 0)
        {
            sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty, 
              timeSpan.Seconds, (timeSpan.Seconds > 1) ? "seconds" : "second");
            if (approximate) return sb.ToString() + suffix;
        }
        if (sb.Length == 0) return "right now";
    
        sb.Append(suffix);
        return sb.ToString();
    }
    
    0 讨论(0)
  • 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";
    
    0 讨论(0)
  • 2020-11-21 06:11

    I would recommend computing this on the client side too. Less work for the server.

    The following is the version that I use (from Zach Leatherman)

    /*
     * Javascript Humane Dates
     * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
     * Re-write by Zach Leatherman (zachleat.com)
     * 
     * Adopted from the John Resig's pretty.js
     * at http://ejohn.org/blog/javascript-pretty-date
     * and henrah's proposed modification 
     * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
     * 
     * Licensed under the MIT license.
     */
    
    function humane_date(date_str){
            var time_formats = [
                    [60, 'just now'],
                    [90, '1 minute'], // 60*1.5
                    [3600, 'minutes', 60], // 60*60, 60
                    [5400, '1 hour'], // 60*60*1.5
                    [86400, 'hours', 3600], // 60*60*24, 60*60
                    [129600, '1 day'], // 60*60*24*1.5
                    [604800, 'days', 86400], // 60*60*24*7, 60*60*24
                    [907200, '1 week'], // 60*60*24*7*1.5
                    [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
                    [3942000, '1 month'], // 60*60*24*(365/12)*1.5
                    [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
                    [47304000, '1 year'], // 60*60*24*365*1.5
                    [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365
                    [4730400000, '1 century'] // 60*60*24*365*100*1.5
            ];
    
            var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
                    dt = new Date,
                    seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
                    token = ' ago',
                    i = 0,
                    format;
    
            if (seconds < 0) {
                    seconds = Math.abs(seconds);
                    token = '';
            }
    
            while (format = time_formats[i++]) {
                    if (seconds < format[0]) {
                            if (format.length == 2) {
                                    return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
                            } else {
                                    return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
                            }
                    }
            }
    
            // overflow for centuries
            if(seconds > 4730400000)
                    return Math.round(seconds / 4730400000) + ' centuries' + token;
    
            return date_str;
    };
    
    if(typeof jQuery != 'undefined') {
            jQuery.fn.humane_dates = function(){
                    return this.each(function(){
                            var date = humane_date(this.title);
                            if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to
                                    jQuery(this).text(date);
                    });
            };
    }
    
    0 讨论(0)
提交回复
热议问题