65.9K
CodeProject is changing. Read more.
Home

How To Convert a Future Date Time to “X minutes from now” in C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

May 9, 2014

CPOL
viewsIcon

14226

How to convert a future date time to "X minutes from now" in C#

In my previous post, we saw how we can convert a Date Time value to “X Minutes Ago” feature using C#. A user interestingly asked me for a function that can do something similar but for future dates. Today, in this post, we will see how we can achieve similar functionality for a future date in C#. In this post, we will write a C# function that will take a DateTime as parameter and return relevant time remaining in future. This can be a good idea for displaying a list of events/sessions on a webpage.

The function to convert DateTime to a “Time From Now” string is as below:

public static string TimeFromNow(DateTime dt)
{
    if (dt < DateTime.Now)
        return "about sometime ago";
    TimeSpan span = dt - DateTime.Now;
    if (span.Days > 365)
    {
        int years = (span.Days / 365);
        return String.Format("about {0} {1} from now", years, years == 1 ? "year" : "years");
    }
    if (span.Days > 30)
    {
        int months = (span.Days / 30);
        return String.Format("about {0} {1} from now", months, months == 1 ? "month" : "months");
    }
    if (span.Days > 0)
        return String.Format("about {0} {1} from now", span.Days, span.Days == 1 ? "day" : "days");
    if (span.Hours > 0)
        return String.Format("about {0} {1} from now", span.Hours, span.Hours == 1 ? "hour" : "hours");
    if (span.Minutes > 0)
        return String.Format("about {0} {1} from now", span.Minutes, 
                             span.Minutes == 1 ? "minute" : "minutes");
    if (span.Seconds > 5)
        return String.Format("about {0} seconds from now", span.Seconds);
    if (span.Seconds == 0)
        return "just now";
    return string.Empty;
}

You can call the function something like below:

        Console.WriteLine(TimeFromNow(DateTime.Now));
        Console.WriteLine(TimeFromNow(DateTime.Now.AddMinutes(5)));
        Console.WriteLine(TimeFromNow(DateTime.Now.AddMinutes(59)));
        Console.WriteLine(TimeFromNow(DateTime.Now.AddHours(2)));
        Console.WriteLine(TimeFromNow(DateTime.Now.AddDays(5)));
        Console.WriteLine(TimeFromNow(DateTime.Now.AddMonths(3)));

The output looks something like below:

date-time-minutes-from-now

Hope this post helps you. Keep learning and sharing!