Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

Code to Turn your TimeSpan into User Readable and Friendly Text

2.90/5 (5 votes)
30 Jan 2014CPOL1 min read 16.9K   40  
A piece of code you can copy paste to transform TimeSpan into user readable UI text

Introduction

Programmers and scientists like numbers, users don't, therefore, I take the steps to convert all numbers in my Web-UI to Colors, Sizes (Progress bars, etc.), Icons and such.
And the case of Date and Time is no exception!

The saying: "sent at 4/5/2012 15:43" has so many issues:

  1. It takes a while to figure out, this is 2 years ago...
  2. Is the hour really meaningful for a 2 year old post?
    Even the day might be neglectable.
  3. No one ever knows if the date is dd/mm/yyyy or mm/dd/yyyy

Background

To provide a better UX, I think Facebook nailed it by stamping posts with readable times such as: few seconds ago, an hour ago, 2 years ago and such.

I built a similar transformation for C# TimeSpan class and wanted to share it with all.

It will provide a string with N parts for each valid part of the TimeSpan as 4 years 3 months is two parts.

Using the Code

Simply copy the class to your code-base and when needed, call the extension method Prettify() on any TimeSpan object.

Example:

C++
DateTime dt = new DateTime(...); // any dateTime
string formatedDate = DateTime.Now.Substract(dt).Prettify(); 

You can control the output by two parameters:

  1. partCount: means how many NON-ZERO parts you want.
  2. neglectionFactor: Don't output a part if it doesn't affect the overall value by this much means if number of years is very high, months become insignificant and will not be displayed.

Note (Localization)

The code is made to work in Hebrew, but is easily translated to any other language and dialect.
Just change the Get*Text(int v) functions to return other values.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)