Example. Prettily-formatted dates can improve a program. To display usable relative and pretty dates, you need to calculate the time elapsed from the original date.
Here The method here receives the original DateTime, and then uses DateTime.Now to calculate the elapsed time.
Start The code in the GetPrettyDate method takes the elapsed days and seconds from the original date.
Next We handle recent dates, in the same day. There is a chain of conditionals that return pretty strings.
Finally We handle more distant dates—the method here doesn't handle months and years.
using System;
class Program
{
static void Main()
{
// Test 90 seconds ago.
Console.WriteLine(GetPrettyDate( DateTime.Now.AddSeconds(-90)));
// Test 25 minutes ago.
Console.WriteLine(GetPrettyDate( DateTime.Now.AddMinutes(-25)));
// Test 45 minutes ago.
Console.WriteLine(GetPrettyDate( DateTime.Now.AddMinutes(-45)));
// Test 4 hours ago.
Console.WriteLine(GetPrettyDate( DateTime.Now.AddHours(-4)));
// Test 15 days ago.
Console.WriteLine(GetPrettyDate( DateTime.Now.AddDays(-15)));
}
static string GetPrettyDate(DateTime d)
{
// Get time span elapsed since the date.
TimeSpan s = DateTime.Now.Subtract(d);
// Get total number of days elapsed.
int dayDiff = (int)s.TotalDays;
// Get total number of seconds elapsed.
int secDiff = (int)s.TotalSeconds;
// Don't allow out of range values.
if (dayDiff < 0 || dayDiff >= 31)
{
return null;
}
// Handle same-day times.
if (dayDiff == 0)
{
// Less than one minute ago.
if (secDiff < 60)
{
return "just now";
}
// Less than 2 minutes ago.
if (secDiff < 120)
{
return "1 minute ago";
}
// Less than one hour ago.
if (secDiff < 3600)
{
return string.Format("{0} minutes ago",
Math.Floor((double)secDiff / 60));
}
// Less than 2 hours ago.
if (secDiff < 7200)
{
return "1 hour ago";
}
// Less than one day ago.
if (secDiff < 86400)
{
return string.Format("{0} hours ago",
Math.Floor((double)secDiff / 3600));
}
}
// Handle previous days.
if (dayDiff == 1)
{
return "yesterday";
}
if (dayDiff < 7)
{
return string.Format("{0} days ago",
dayDiff);
}
if (dayDiff < 31)
{
return string.Format("{0} weeks ago",
Math.Ceiling((double)dayDiff / 7));
}
return null;
}
}1 minute ago
25 minutes ago
45 minutes ago
4 hours ago
3 weeks ago
Summary. We looked at how to display well-formatted and human-readable pretty dates. This code is mainly a finishing touch for your applications. It can improve usability.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.