我可以检查字符串是否包含日期吗?像任何约会一样 [英] Can I check if a string contains a date? Like any date
问题描述
我在数据库中的表包含日期。
i想要从记录中删除日期,如果它们是从今天之前,即昨天或前天等等......
i知道我可以通过分割单词在字符串中找到日期。
现在如何从今天之前删除那个日期(我在字符串中通过拆分找到的日期)?
我的尝试: < br $>
My table in database contains dates.
i want to remove the dates from the record if they are from before today i.e yesterday or day before yesterday and so on...
i know i can find a date in a string by splitting the word.
now how can i remove THAT date(date which i found in the string by splitting) if it is from before today??
What I have tried:
while (READ.Read())
{
string date = READ.GetString(h);
DateTime dt;
string[] words = date.Split(' ');
bool found = false;
foreach (string word in words)
{
if (DateTime.TryParse(word,out dt))
{
l = word;
found = true;
break;
}
if(found)
{
result = DateTime.Compare(l, DateTime.Today);//error cannot compare string with datetime..
}
}
推荐答案
你需要使用Regex(常规)表达式)来确定这一点。查看 this [ ^ ]谷歌搜索开始。
另见 this [ ^ ] CP回答快速解决方案。
/ ravi
You'll need to use Regex (regular expressions) to determine this. See the results of this[^] Google search to get started.
Also see this[^] CP answer for a quick solution.
/ravi
不容易,甚至不可靠。
问题是如果你是你不知道日期在哪里,或者甚至不知道它的长度,那么你可能不知道它的格式是什么 - 这会导致很大的问题。
你给出的例子是容易发现:在空格上分割字符串并检查每个单词以查看它是否作为日期值进行解析:
Not easily, or even reliably.
The problem is that if you don;t know where the date is, or even ho0w long it it, then you presumably don't know what format it is in either - and that causes big problems.
The example you give is easy to spot: split the string on a space and check each "word" to see if it Parses as a Date value:
DateTime dt;
string[] words = input.Split(' ');
bool found = false;
foreach (string word in words)
{
if (DateTime.tryParse(word, out dt))
{
found = true;
break;
}
但是......如果日期是免费形式,那么用户输入你好今天的日期是2017年7月16日!的原因是什么?即使进行复杂的检查,也很难找到约会。
如果我是你,我会重新设计输入机制,使日期来自拣货员,而不是解析自由格式文本。
But ... if the date is free form, then what stops the user entering "Hello today's date is 16th of July, 2017!"? And that's hard to find as a date, even with sophisticated checking.
If I was you, I'd redesign the input mechanism to make dates come from pickers, rather than parsing free form text.
如果你能找到日期部分来自字符串,你知道存储在数据库表中的日期格式然后我认为你可以简单地使用parsedate方法将字符串转换为日期,然后使用下面的代码将其与当前日期进行比较。
if(dateFoundInDB.Date == DateTime.Now.Date)
如果此条件为真,请使用string.remove(dateFoundInDB)to从字符串中删除日期。
If you can find the date part from the string and you know the format of date stored in database table then I think you can simply use parsedate method to convert the string to date and then compare it with current date using below code.
if(dateFoundInDB.Date ==DateTime.Now.Date)
if this condition is true use string.remove(dateFoundInDB) to remove the date from the string.
这篇关于我可以检查字符串是否包含日期吗?像任何约会一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!