【问题标题】:How to get a DateTime in a random string?如何在随机字符串中获取日期时间?
【发布时间】:2015-10-05 13:37:50
【问题描述】:

给了我一堆告诉我一个事件的字符串,我需要将所有字符串转换为开始 DateTime 和结束 DateTime。起初,我尝试逐个字符地遍历字符串,但是当字符串中有多个日期时,它变得太复杂了。我也尝试解析许多日期格式,但是当日期和月份首先出现时,然后是时间,它不起作用。我正在使用 C#,并且还尝试使用 Regex 搜索字符串,但我遇到了麻烦,因为我无法将日期与正确的时间匹配。

下面是我给出的几个字符串示例:

2015 年 9 月 12 日至 13 日,星期六上午 10:30 至下午 6 点。周日中午 10 点

应该有 2 个日期:

StartDate: 2015/09/12 10:30 EndDate: 2015/09/12 18:00
StartDate: 2015/09/13 10:00 EndDate: 2015/09/13 12:00

2015 年 6 月 3 日至 9 月 9 日,周二至周四下午 6 点至 7 点,周日上午 10 点到 11 点

星期二/星期四/星期日的多个日期,日期范围:

StartDate: 2015/06/04 18:00 EndDate: 2015/06/04 19:00
StartDate: 2015/06/07 10:00 EndDate: 2015/06/07 11:00
StartDate: 2015/06/09 18:00 EndDate: 2015/06/09 19:00
StartDate: 2015/06/11 18:00 EndDate: 2015/06/11 19:00

...继续遵循相同的模式

谢谢。

【问题讨论】:

  • 似乎是一个令牌的工作......首先尝试将可能的格式概括为规则。
  • 试试标准日期时间解析模块之一是否适合您。例如,Perl 有一些:search.cpan.org/~gbarr/TimeDate-2.30/lib/Date/Parse.pm 如果没有,另一种选择是设计一个具有可能日期格式的小型 DSL(领域特定语言),并使用 ANTLR 或 Flex/Bison 等解析器生成器来生成代码。
  • 当日期格式如此多样时,可能的日期格式是什么?有些字符串以时间开头,以月份结尾,依此类推。
  • 为什么第一个字符串"Sunday 10 a.m. noon"的结束时间是12:00

标签: c# date datetime


【解决方案1】:

这是解决此问题的一种可能方法:

1) 扫描/词法分析 -> 扫描基本令牌。

Names: September, Saturday, AM, etc.
Numbers: 12, 2015, 9, etc.
Operators serving as Separators: '-', ',', space, etc.
   '-' acts as a range operator as in FromDate - ToDate.
   ',' and space separate components of a date

2) 解析 -> 用标记构建解析树。

Names are classified into Months, days of week, etc.
Numbers are identified as year, month or day if it 
can be done unambiguously. Otherwise, their identification 
is left to later steps.
We can use some heuristics, like day of month almost always follows month.

3) 现在,解析树表示由“-”分隔的日期时间条目。

At this point, a date in the tree can be partial or complete.
Introduce separator when it is missing between adjacent dates or times.
"Sunday 10a.m noon" is missing separator between '10am' and 'noon'

4) 从解析树中识别完整和部分日期。

For example, "September 9, 2015" is a complete date, while "June 3"
is incomplete. After extracting at least one complete date, infer 
the missing elements in incomplete dates from surrounding context.
"June 3" is incomplete because of missing year, so we grab the 
year from the nearest complete date as 2015. 

5) 如果在上述步骤中找不到完整的日期,

Use two adjacent dates and let them fill in missing parts
from each other to arrive at a complete one. "September 12 - 13, 2015" 
is one such example. Left side of the separator is missing 
year and can get it from right side. Figure out the date for 
a day of week, like Thursday from the complete date in the string

【讨论】:

  • 只是好奇,您能否描述一下针对此问题实施的解决方案的高级设计?
猜你喜欢
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 2016-03-06
  • 2015-05-11
  • 2022-06-14
  • 1970-01-01
相关资源
最近更新 更多