tags:

views:

343

answers:

5

Is there a library that exists that will parse human readable timespans into a .net TimeSpan?

I need something that will parse strings like

30 days
1 week
5 hours

Does such a thing exist? Its probably not too hard to write myself, but if something is out there, it would be so much easier!

I currently don't need functionality like "30 days, 3 hours, 5 minutes", just the one value, but it couldn't hurt!

+1  A: 

Well, I know that datejs the javascript code works really well for dates like that. You could look at it for inspiration for C# code. Not sure if that helps that much though; but might be interesting.

See www.datejs.com

Robert Massaioli
A: 

this is the available parsing ways for date and time:

Parsing Date and Time Strings

Wael Dalloul
A: 

I know that you were looking for a library to do this but it seems the people that like this syntax are ruby developers and well they stick to Ruby. If you really want to do this ,its pretty simple to do something similiar with .Net Extensions that is a bit more readable. Have a look at this article http://haacked.com/archive/2007/05/24/ruby-like-syntax-in-c-3.0.aspx

Also if you dont like the syntax in the article then all you need to do is create a parser that converts down to ticks , which can be used by the timespan constructor class.

RC1140
+3  A: 

I took a crack at this sometime back, I was playing with parsers as I knew nothing about them so don't expect quality. But you can get the code here: http://timestamper.codeplex.com/

I havent looked at it for a while, but im pretty sure it can do all the things that you mentioned above.

Edit:

Just noted that you wanted a timespan object returned and not a date time. The code I provided will return a DateTime reletive to today i.e.

"2 days" will be: DateTime.Now.AddDays(2);

At least I think this is what is did, can quite be sure. If this is the case, you should just be able to get the timespan between the two DateTimes.

Owen
Awesome, thanks Owen. While I've gone and written a *very* simple parser for TimeSpan in the meanwhile, this is a very handy library to have around!
Gareth
No worries. Actually, if you need it to do anything more I may have another play with it at some point in time.
Owen
A: 

It's not directly applicable, but my company has developed a .NET library that does this for dates. A counterpart that works for spans (more or less exactly what you are asking for) is planed for "when we get around to needing it". If there is enough interest, that could become sooner.

BCS
. . . . who's website is written in php? :D
andrewWinn
Last I checked, the website is generated using a costume tool. but to avoid breaking links, the PHP extension is still used. Anyway we're a mixed shop for somethings.
BCS
no worries, friendly jab :)
andrewWinn
Thats because that's what php is good for, customer facing websites with very little interesting happening under the hood.
Owen