Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse multiple formats with Noda Time?

Tags:

nodatime

I like the Noda Time handling of formatting and parsing values using the various *Pattern types in the NodaTime.Text namespace. However, user input is often not as regular as a single format. For example, our app uses the time format "h:mm tt" but we would like to be able to parse user input in any of the following formats:

  • h:mm tt
  • h:mmtt (no space)
  • h:mm t
  • h:mmt (no space)
  • h tt
  • hh:mm
  • and so on...

Is there a way to use Noda Time to parse input that may be in any of a number of formats?

like image 816
Jeff Walker Code Ranger Avatar asked Nov 09 '12 21:11

Jeff Walker Code Ranger


1 Answers

(Sorry for taking so long to respond to this.)

Annoyingly, it looks like we haven't exposed this.

It's present in Noda Time in the CompositePattern class. Unfortunately that's currently internal. I've raised issue 147 to fix this at some point (probably in the 1.1 time frame).

For the moment, it's probably easiest to just use the same code from CompositePattern - you needn't create your own IPattern<T> implementation for this, as it's only really the Parse method which is useful. (Indeed, you could even write it as an extension method on IEnumerable<IPattern<T>>, although I'm not sure offhand whether we've given enough visibility to create the same kind of failure result.)

like image 177
Jon Skeet Avatar answered Nov 18 '22 19:11

Jon Skeet