简体   繁体   中英

how do I compare two dates?

We would like to compare a date from the db with current date.

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.


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:

Year(eventdate) = Year(current_timestamp)

If drv has an instance of DataReader then verify 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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