Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

c# - How to parse relative time?

This question is the other side of the question asking, "How do I calculate relative time?".

Given some human input for a relative time, how can you parse it? By default you would offset from DateTime.Now(), but could optionally offset from another DateTime.

(Prefer answers in C#)

Example input:

  • "in 20 minutes"
  • "5 hours ago"
  • "3h 2m"
  • "next week"

Edit: Let's suppose we can define some limits on the input. This sort of code would be a useful thing to have out on the web.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A Google search turns up the parsedatetime library (associated with the Chandler project), which is designed to do exactly this. It's open source (Apache License) and written in Python. It seems to be quite sophisticated -- from the homepage:

parsedatetime is able to parse, for example, the following:

* Aug 25 5pm
* 5pm August 25
* next saturday
...
* tomorrow
* next thursday at 4pm
* at 4pm
* eod
* in 5 minutes
* 5 minutes from now
* 5 hours before now
* 2 days from tomorrow

Since it's implemented in pure Python and doesn't use anything fancy, there's a good chance it's compatible with IronPython, so you could use it with .net. If you want specifically a C# solution, you could write something based on the algorithms they use...

It also comes with a whole bunch of unit tests.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...