Returns a humanized string indicating how long ago something happened, eg "3 days ago". For future dates, returns when this DateTime will occur from DateTime.UtcNow. - CSharp System

CSharp examples for System:DateTime Day

Description

Returns a humanized string indicating how long ago something happened, eg "3 days ago". For future dates, returns when this DateTime will occur from DateTime.UtcNow.

Demo Code



public class Main{
        /// <summary>
        ///     Returns a humanized string indicating how long ago something happened, eg "3 days ago".
        ///     For future dates, returns when this DateTime will occur from DateTime.UtcNow.
        /// </summary>
        public static string ToRelativeTime(this DateTime dt, bool includeTime = true, bool asPlusMinus = false,
            DateTime? compareTo = null, bool includeSign = true)
        {//from w  ww  . j a  v  a  2 s .c  o  m
            var comp = compareTo ?? DateTime.UtcNow;
            if (asPlusMinus)
                return dt <= comp
                    ? ToRelativeTimeSimple(comp - dt, includeSign ? "-" : "")
                    : ToRelativeTimeSimple(dt - comp, includeSign ? "+" : "");
            return dt <= comp
                ? ToRelativeTimePast(dt, comp, includeTime)
                : ToRelativeTimeFuture(dt, comp, includeTime);
        }
}

Related Tutorials