returns how long something took in years, months, or days - CSharp System

CSharp examples for System:DateTime Year

Description

returns how long something took in years, months, or days

Demo Code


using System;/*from   w w  w.j  av a  2s.co m*/

public class Main{
        /// <summary>
        /// returns how long something took in years, months, or days
        /// </summary>
        public static string TimeTakenLong(this DateTime? dt)
        {
            if (dt == null) return "";
            return TimeTakenLong(dt.Value);
        }
        /// <summary>
        /// Returns how long something took in years, months, or days
        /// </summary>
        public static string TimeTakenLong(this DateTime dt)
        {
            int days = (DateTime.UtcNow - dt).Days;
            if (days <= 0)
                return "today";
            if (days <= 1)
                return "yesterday";
            if (days > 365)
            {
                return (days / 365) + " year" + ((days / 365) > 1 ? "s ago" : " ago");
            }
            if (days > 30)
            {
                return (days / 30) + " month" + ((days / 30) > 1 ? "s ago" : " ago");
            }
            return days + " day" + (days > 1 ? "s ago" : " ago");
        }
}

Related Tutorials