Skip to content

A TimeSpan that can be defined as a string in configuration files, and easy to read.

License

Notifications You must be signed in to change notification settings

thomhurst/ReadableTimeSpan

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

80 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ReadableTimeSpan

A TimeSpan that can be defined as a string in configuration files, and easy to read.

nuget Codacy Badge

Why?

Sometimes we want to define TimeSpans in our appsettings.json (or other configuration) files - And that requires stringified TimeSpans. The problem is, they look something like this:

  • 00:01:00
  • 1.00:01:00.100

Does that mean 1 hour? 1 minute? 1 second? Even if you know, it can be very easy to accidentally set the wrong value. So this let's you write TimeSpans in human readable language, and it'll do the conversion for you!

So I can instead write like:

  • 1 minute
  • 1m
  • 1 day & 1 minute & 100 milliseconds
  • 1d + 1m + 100ms

How can I write them?

The syntax is: {number}{optional space}{unit}

If you want to combine units, such as seconds and milliseconds, that's possible too, by using separators.

That would be more like: {number}{optional space}{unit} {separator} {number}{optional space}{unit}

Separators can be:

  • :
  • +
  • &
  • |
  • -
  • and

The units can be:

    T,
    Tick,
    Ticks,
    
    Ms,
    Mil,
    Mils,
    Milli,
    Millis,
    Millisecond,
    Milliseconds,
    
    S,
    Sec,
    Secs,
    Second,
    Seconds,
    
    M,
    Min,
    Mins,
    Minute,
    Minutes,
    
    H,
    Hr,
    Hrs,
    Hour,
    Hours,
    
    D,
    Day,
    Days

So a perfectly valid TimeSpan could look like:

  • 166 days | 13 hrs | 42 min | 29 seconds and 324ms
  • 166d + 13h + 42m + 29s + 324ms

What else do I need to do?

ReadableTimeSpan works with IConfiguration and Binding. So if you use Microsoft ConfigurationBuilder or IOptions, the conversion from appsettings.json to Application Code happens automatically. All you need to do, is BEFORE you bind any config, call this static method: ReadableTimeSpan.EnableConfigurationBinding();

If you want to use it outside of Configuration Binding, simply call either:

  • ReadableTimeSpan.Parse
  • ReadableTimeSpan.TryParse

ToReadableString()

ToReadableString() will give you a string version of the TimeSpan, but with words instead of just numbers.

About

A TimeSpan that can be defined as a string in configuration files, and easy to read.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published