2015-10-04 38 views
2

我收到了一串字符串,告诉我有关事件,我需要将所有字符串转换为开始DateTime和结束DateTime。起初,我尝试通过字符串逐个字符,但当字符串中有多个日期时,它变得太复杂了。我也尝试过分析许多日期格式,但是当日期和月份先来时,那么时间,它不起作用。我正在使用C#,并且也尝试使用正则表达式搜索字符串,但是我遇到了麻烦,因为我无法将日期匹配到正确的时间。如何获取随机字符串中的日期时间?

这里是我给出的字符串的几个例子:

九月12-13,2015,周六10:30 a.m.-6p.m.周日上午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 

六月3日至9月9日,2015年,周二,周四下午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 

...继续以下相同的模式

谢谢。

+1

似乎是令牌的工作......第一次尝试推广可能的格式转换成规则。 –

+0

如果其中一个标准日期 - 时间分析模块适合您,请尝试。例如,Perl有一些:http://search.cpan.org/~gbarr/TimeDate-2.30/lib/Date/Parse.pm如果不是,另一个选择是设计一个小的DSL(领域特定语言)日期格式,并使用像ANTLR或Flex/Bison这样的解析器生成器来生成代码。 –

+1

当可能的日期格式如此多样时,可能的日期格式会是什么?有些字符串以时间开始,以月份结束,等等。 – Scott

回答

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)解析 - >从标记中构建一个解析树。 3)现在,Parse树表示由' - '分隔的日期时间条目。

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 
+0

只是好奇,你能描述为这个问题实施的解决方案的高层次设计吗? –

相关问题