TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Pretty Date Formatting

This C# example code displays friendly dates using code-behind in ASP.NET. This enhances usability and friendliness.

Pretty dates are easier to read.

They are nicely formatted. We can show "1 hour ago" or "1 minute ago", instead of seconds. We implement a pretty date method for use in ASP.NET or Windows programs.

Example. Prettily-formatted dates are sometimes overlooked in ASP.NET or Windows applications. This final touch can improve your program. To display usable relative and pretty dates, you need to calculate the time elapsed from the original date.

So: The method here receives the original DateTime, and then uses DateTime.Now to calculate the elapsed time.

DateTime.Now

C# program that displays pretty dates

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)
    {
	// 1.
	// Get time span elapsed since the date.
	TimeSpan s = DateTime.Now.Subtract(d);

	// 2.
	// Get total number of days elapsed.
	int dayDiff = (int)s.TotalDays;

	// 3.
	// Get total number of seconds elapsed.
	int secDiff = (int)s.TotalSeconds;

	// 4.
	// Don't allow out of range values.
	if (dayDiff < 0 || dayDiff >= 31)
	{
	    return null;
	}

	// 5.
	// Handle same-day times.
	if (dayDiff == 0)
	{
	    // A.
	    // Less than one minute ago.
	    if (secDiff < 60)
	    {
		return "just now";
	    }
	    // B.
	    // Less than 2 minutes ago.
	    if (secDiff < 120)
	    {
		return "1 minute ago";
	    }
	    // C.
	    // Less than one hour ago.
	    if (secDiff < 3600)
	    {
		return string.Format("{0} minutes ago",
		    Math.Floor((double)secDiff / 60));
	    }
	    // D.
	    // Less than 2 hours ago.
	    if (secDiff < 7200)
	    {
		return "1 hour ago";
	    }
	    // E.
	    // Less than one day ago.
	    if (secDiff < 86400)
	    {
		return string.Format("{0} hours ago",
		    Math.Floor((double)secDiff / 3600));
	    }
	}
	// 6.
	// 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;
    }
}

Output

1 minute ago
25 minutes ago
45 minutes ago
4 hours ago
3 weeks ago

First, we see the Main method, which tests the method for accuracy. We can establish that the method works by its output. The first three steps in the GetPrettyDate method take the elapsed days and seconds from the original date.

Note: This is a standard way to calculate elapsed time. In the method, TotalDays and TotalSeconds are used.

Days Elapsed From DateTime

Steps in example. Step 5 handles very recent dates, in the same day. You can see in parts A - E that there is a chain of conditionals that return pretty strings. Finally, step 6 handles more distant dates.

Warning: The method, like the original by John Resig, doesn't handle months and years.

string.Format Method

Original. I wanted to follow the logic in the original pretty.js JavaScript code, because I felt it would be best to follow the same rules. This way, you can swap the two methods and use one on the ASP.NET server and the other in JavaScript.

JavaScript Pretty Date: ejohn.org

Note: Thanks to John Resig for the original code and inspiration. His code is under the MIT license.

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 is something that I wished I had when rushing to complete a project.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf