How to Calculate relative time in C#

In this article, learn how to Calculate relative time in C# by using simple inbuilt Math functions. The relative time text such as for now, less than a minute, about a minute, about an hour, about a month, about a year are calculated.


Calculate relative time in C#:


/// 
/// Function to calculate the relative date for the given date time which is older than today's date. (C# 6)
/// 
/// DateTime object which is older than today's date
/// The relative date
public static string ToRelativeDate(DateTime dtOldDateTime)
{
    TimeSpan oSpan = DateTime.Now.Subtract(dtOldDateTime);
    double TotalMinutes = oSpan.TotalMinutes;
    string sSuffix = " ago";

    if (TotalMinutes < 0.0)
    {
        TotalMinutes = Math.Abs(TotalMinutes);
        sSuffix = " from now";
    }

    var aValue = new SortedList>();
    aValue.Add(0.75, () => "less than a minute");
    aValue.Add(1.5, () => "about a minute");
    aValue.Add(45, () => string.Format("{0} minutes", Math.Round(TotalMinutes)));
    aValue.Add(90, () => "about an hour");
    aValue.Add(1440, () => string.Format("about {0} hours", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24
    aValue.Add(2880, () => "a day"); // 60 * 48
    aValue.Add(43200, () => string.Format("{0} days", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30
    aValue.Add(86400, () => "about a month"); // 60 * 24 * 60
    aValue.Add(525600, () => string.Format("{0} months", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365 
    aValue.Add(1051200, () => "about a year"); // 60 * 24 * 365 * 2
    aValue.Add(double.MaxValue, () => string.Format("{0} years", Math.Floor(Math.Abs(oSpan.TotalDays / 365))));

    return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + sSuffix;
}

Try yourself:



- Article ends here -

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   Singleton design pattern in C#
Share this:
We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo