Awesome
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).
Help needed
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:
- PengoWray's post with the original concept and motivation for TimeSpanParser.
- QuickGuide.cs — Read through the comments for a tour of the more advanced usage and options. This UnitTest is written as a tutorial.
- WildTests.cs — Examples of timespans found in the wild.
- To-do list (Wiki)