如何解析相对时间? [英] How to parse relative time?

查看:113
本文介绍了如何解析相对时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是问题的另一面,询问"如何计算相对时间?".

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

给出一段相对时间的人工输入,您如何解析它?默认情况下,您可以从DateTime.Now()偏移,但是可以选择与另一个DateTime偏移.

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.

(首选C#答案)

示例输入:

  • 在20分钟内"
  • "5小时前"
  • "3h 2m"
  • 下周"

让我们假设我们可以为输入定义一些限制.这类代码在网络上发布是很有用的.

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.

推荐答案

这正在构建用于日期处理的DSL(特定于域的语言).我不知道是否有人为.NET做过一个,但是DSL的构建非常简单:

That's building a DSL (Domain specific language) for date handling. I don't know if somebody has done one for .NET but the construction of a DSL is fairly straightforward:

  1. 准确定义语言,您将接受的输入形式以及歧义处理
  2. 构建语言的语法
  3. 构建将您的语言解析为可行的AST的有限状态机

您可以自己完成所有操作(借助于《龙书》 )或使用工具来达到效果,如

You can do all that by yourself (with the help of the Dragon Book, for instance) or with the help of tools to the effect, as shown in this link.

只需通过认真思考各种可能性,借助良好的UI示例,即可覆盖应用程序将收到的实际输入的一半以上.如果您打算接受人类可能键入的所有内容,则可以记录确定为歧义的输入,然后在可以解释它们时将它们添加到语法中,因为有些事物本来就是歧义的.

Just by thinking hard about the possibilities you have a good chance, with the help of good UI examples, of covering more than half of the actual inputs your application will receive. If you aim to accept everything a human could possibly type, you can record the input determined as ambiguous and then add them to the grammar, whenever they can be interpreted, as there are things that will be inherently ambiguous.

这篇关于如何解析相对时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆