Returns a very *small* humanized string indicating how long ago something happened, eg "3d ago" - CSharp System

CSharp examples for System:DateTime Format

Description

Returns a very *small* humanized string indicating how long ago something happened, eg "3d ago"

Demo Code


using System;//from w  w w.  java 2s .c  om

public class Main{
        #endregion

        /// <summary>
        /// Returns a very *small* humanized string indicating how long ago something happened, eg "3d ago"
        /// </summary>
        public static string ToRelativeTimeMini(this DateTime dt)
        {
            var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
            double delta = ts.TotalSeconds;

            if (delta < 60)
            {
                return ts.Seconds + "s ago";
            }
            if (delta < 3600) // 60 mins * 60 sec
            {
                return ts.Minutes + "m ago";
            }
            if (delta < 86400) // 24 hrs * 60 mins * 60 sec
            {
                return ts.Hours + "h ago";
            }
            int days = ts.Days;
            if (days <= 2)
            {
                return days + "d ago";
            }
            else if (days <= 330)
            {
                return dt.ToString("MMM %d 'at' %H:mmm").ToLowerInvariant();
            }
            return dt.ToString(@"MMM %d \'yy 'at' %H:mmm").ToLowerInvariant();
        }
}

Related Tutorials