Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan to friendly string library (C#)

Tags:

c#

timespan

Does anyone know of a good library (or code snippet) for converting a TimeSpan object to a "friendly" string such as:

  • Two years, three months and four days
  • One week and two days

(It's for a document expiry system, where the expiry could be anything from a few days to several decades)

Just to clarify, say I had a TimeSpan with 7 days, that should print "1 week", 14 days "2 weeks", 366 days "1 year and 1 day", etc etc.

like image 500
Keith Williams Avatar asked Jul 16 '09 16:07

Keith Williams


1 Answers

I know this is old, but I wanted to answer with a great nuget package.

Install-Package Humanizer

https://www.nuget.org/packages/Humanizer

https://github.com/MehdiK/Humanizer

Example from their readme.md

TimeSpan.FromMilliseconds(1299630020).Humanize(4) => "2 weeks, 1 day, 1 hour, 30 seconds"

@ian-becker Needs the credit

like image 182
Lord Darth Vader Avatar answered Sep 29 '22 07:09

Lord Darth Vader