Skip to content

Getting started with HumanTimeParser.English

Zack Broderson edited this page Apr 30, 2021 · 2 revisions

Getting Started With HumanTimeParser.English


The EnglishTimeParser is the main component of this package and is designed to be used as a singleton.

To get started using the parser take a look at the following example.

// instantiate a reusable time parser.
var parser = new EnglishTimeParser();
// returns a generic ITimeParsingResult
var result = parser.Parse("6 minutes from now"); 

// to determine if the result is successful or not we pattern match.  Pattern matching for DefaultTimeParsingResult also works.
if (result is ISuccessfulTimeParsingResult<DateTime> successfulResult) 
{
  // sucessfulResult.Value will represent a time 6 minutes from DateTime.Now
  Console.WriteLine(successfulResult.Value); 
}

Now, this is great if all you need is a parsed DateTime object, but what if you need the input from the user without all the time jargon?

Luckily the FirstParsedTokenIndex and LastParsedTokenIndex provided on an ISuccessfulTimeParsingResult can be utilized for just that.

These two properties represent the index of the character the parser started parsing at and ended parsing at, respectively of course. Take this snippet for example.

// instantiate a reusable time parser.
var parser = new EnglishTimeParser();
// returns a generic ITimeParsingResult
var result = parser.Parse("in 6 minutes I will leave"); 

// to determine if the result is successful or not we pattern match.
if (result is ISuccessfulTimeParsingResult<DateTime> successfulResult) 
{
    // holds the user input with the time jargon stripped from it
    var userInput = successfulResult.LastParsedTokenIndex == value.Length ?
        value[..successfulResult.FirstParsedTokenIndex] : 
        value[successfulResult.LastParsedTokenIndex..];

    // make sure to trim the whitespace off the string
    Console.WriteLine(userInput.Trim()); // "I will leave" is printed to the console!
}
Clone this wiki locally