Skip to content

Repository files navigation

TimeSpanParser

TimeSpanParser parses human-written and natural language time span strings. For example:

TimeSpanParser.Parse("5 mins")

TimeSpan.Parse("00:05:00") returns the same result with C#'s built-in parser.

TimeSpanParser accepts a number of formats, such as

TimeSpanParser.Parse("2h10m58s") == TimeSpanParser.Parse("2:10:58") == TimeSpanParser.Parse("2 hours, 10 minutes 58 seconds") == TimeSpanParser.Parse("2:10 58s")

Features

  • Does flexible user input for timespan (duration) parsing.
  • Accepts expressions like "1h30m" or "1:30:00" or "1 hour 30 minutes"
  • Also accepts whatever .NET's TimeSpan.Parse() will accept (US and common formats only for now)
  • Accepts a variety of unusual inputs like "-1.5hrs", "3e1000 seconds", and even strings like "3.17:25:30.5" [in case you missed it, the strangest thing about that last example is it uses a dot rather than a colon to separate the days from the hours, which is oddly Microsoft's default way of outputting TimeSpans ("c"). Also it's using fullwidth Unicode characters.]
  • Can round-trip English expressions from TimeSpan.Humanizer()
  • Sane, permissive defaults for unambiguous input, but many options to fine tune if you really want.
  • By changing the default options, you can change the expected units, e.g. you can have it treat a bare input of "5" as "5 minutes" instead of throwing an exception; or treat "3:22" as 3m22s instead of the default which would be the equivalent of 3h22m.
  • Will parse "0 years" and "0 months" unambiguously, as such inputs won't change in meaning even on a leap day during a leap year. Other values for years/months are not currently accepted.
  • Many, many unit tests—many of which pass!
  • Returns a TimeSpan (struct), so shares its limitations — min/max value: approx ±10 million days. Smallest unit: 100 nanoseconds (aka "1 microsoft tick". There are 10 million ticks per second).

PRs welcome.

  • If you find any input TimeSpanParser.Parse(string) does not parse correctly, especially if it differs from TimeSpan.Parse(string), then please create a new issue or add a unit test.

See also:

About

.NET parser library for human-written time spans

Resources

Stars

40 stars

Watchers

5 watching

Forks

Releases

Packages

Used by

Contributors

Languages