Friday, July 6, 2012

Compares to DateTimes and converts the result to an easy human readable

Take this:2012-07-13 17:47:33

and turn it into this:5 minutes 16 seconds ago

   /// 
    /// Compares to DateTimes and converts the result to an easy human readable format.
    /// 
    /// A past or future DateTime.
    /// Relative to this time.
    /// 
    public static string ToRelativeTime(this DateTime time, DateTime relativeTo)
    {
        TimeSpan ts = relativeTo.Subtract(time).Duration();
        string DateFormat = "d MMMM";
        string dir = (relativeTo > time) ? "Ago" : "To go";

        if (relativeTo.Year != time.Year)
            DateFormat += " yyyy";

        if (ts.Days < 360)
        {
            //Months
            if (ts.Days >= 30)
                return string.Format("{0} ({1} Months {2})", time.ToString(DateFormat), (int)(ts.Days / 30), dir);

            //Days
            if (ts.Days > 0)
                return string.Format("{0} ({1} Days {2})", time.ToString(DateFormat), ts.Days, dir);

            //hours
            if (ts.Hours > 0)
                return string.Format("{0} Hours {1} Minutes {2}", ts.Hours, ts.Minutes, dir);

            //minutes
            if (ts.Minutes > 0)
                return string.Format("{0} Minutes {1} Seconds {2}", ts.Minutes, ts.Seconds, dir);

            //seconds
            return string.Format("{0} Seconds {1}", ts.Seconds, dir);
        }

        return time.ToString(DateFormat);
    }

No comments:

Post a Comment