C# Library to parse human readable time spans

2019-02-08 14:00发布

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!

标签: c# parsing date
6条回答
迷人小祖宗
2楼-- · 2019-02-08 14:31

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.

查看更多
贼婆χ
3楼-- · 2019-02-08 14:32

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

查看更多
Bombasti
4楼-- · 2019-02-08 14:37

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.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-02-08 14:40

this is the available parsing ways for date and time:

Parsing Date and Time Strings

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-02-08 14:43

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.

查看更多
Luminary・发光体
7楼-- · 2019-02-08 14:53

I am working on a library on the Dotnet framework (and dotnet core) primarily based on timestamper.

Install from Nuget: HumanDateParser

Usage: (returns System.DateTime)

DateParser.Parse("1 month ago")
DateParser.Parse("after 15 days")
DateParser.Parse("15th feb 2010 at 5:30pm")
查看更多
登录 后发表回答