简体   繁体   English

我该如何比较两个日期?

[英]how do I compare two dates?

We would like to compare a date from the db with current date. 我们想比较db中的日期和当前日期。

Here is what I have tried so far: 这是我到目前为止所尝试的:

'Obtain current date 

Dim curdate As String = Now.ToString("yyyy")

'Now compare curdate with date from db called eventdate. Event date is of dateTime datatype.

If drv("eventdate").ToString = "" And Year(drv("eventdate").ToString) = curdate Then

 'Then do some processing
End if

When I run this code, I get following error: 当我运行此代码时,我收到以下错误:

Conversion from string "" to type 'Date' is not valid. 从字符串“”到“日期”类型的转换无效。

Please help! 请帮忙!

Thank you very much experts. 非常感谢专家。

If Today.CompareTo(CDate(drv("eventdate")).Date) = 0 Then
    'Do something
End If

I'm making the assumption here that you only care about the day, and not the time. 我在这里假设你只关心这一天,而不关心时间。 Otherwise, the odds of having a match within a given day would be about 1 in 2.5 million. 否则,在给定日期内匹配的几率约为250万。


Based on the comment: 根据评论:

If Today.Year.CompareTo(CDate(drv("eventdate")).Year) = 0 Then
    'Do something
End If

or 要么

If Today.Year = CDate(drv("eventdate")).Year Then
    'Do something
End if

And one more thing: it really sounds like this is a check that should be done by your database . 还有一件事:听起来这是一个应该由您的数据库完成的检查。 Make it part of the query that returns the results. 使其成为返回结果的查询的一部分。 This will be much faster, and it's where that kind of check belongs. 这将是更快 ,而且也正是这种检查属于。 All you'd need is add a check to your where clause like so: 你只需要在你的where子句中添加一个检查,如下所示:

Year(eventdate) = Year(current_timestamp)

If drv has an instance of DataReader then verify DBNull . 如果drv有一个DataReader实例,那么验证DBNull

IF Not drv.IsDBNull(column_index_of_eventdate) Then
   ...
   If drv.GetDateTime(column_index).Year=Date.Now.Year Then
        ...
   End If
End If

I believe you have either a null or empty value, also your comparisn is wrong, try: 我相信你有一个空值或空值,你的比较也是错误的,试试:

If drv("eventdate").ToString <> "" Andalso Year(drv("eventdate").ToString) = curdate Then

 'Then do some processing
End if

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM