Hire Me

TimeSpanExtensions .ToFriendlyString()

A C# .NET extension method showing how to convert a TimeSpan interval into a friendly string format

Posted on Sunday, December 7, 2014 at 4:53 PM into csharp code by Steve Woods

This post details a nice little snippet I found on StackOverflow a while back called ToFriendlyString() which attaches to a TimeStamp object and outputs the interval in a nice friendly string format which is customisable, depending on how deep you want to go.

The Code


To use the code simply attach it to a TimeStamp object as follows:

DateTime now = DateTime.Now;
DateTime then = DateTime.Now.AddHours(24);
TimeSpan difference = then.Subtract(now);

Response.Write(difference.ToFriendlyString(1)); // will output "24 hours"
Response.Write(difference.ToFriendlyString(2)); // will output "24 hours, 0 minutes"
Response.Write(difference.ToFriendlyString(3)); // will output "24 hours, 0 minutes, 0 seconds";




Please consider what you post!
Chillax if you're angry.