Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing nullable DateTime's in VB.net

Tags:

c#

asp.net

vb.net

I am a c#/asp.net developer and I am having to work on a VB/asp.net. I started out with VB.NET but after years away from it I'm getting confused with the syntax.

I have two variables

Dim originalDate as DateTime?
Dim newDate as DateTime?

Both nullable datetimes, originalDate is a nullable date I am getting from the database and newDate time is set in code, I need to compare them, they can either both have dates, neither have dates or one have and one not.

I have a bit of code as follows:

if origEndDate = origEndDate then

When both origEndDate and origEndDate are "nothing" this statement is false (well when I run it in the watch window it comes back as nothing)!

I don't understand why this is the case because I was under the impression doing an "=" compares the two values and as they are the same surely it should be true?

Can someone explain what I am doing wrong? What syntax should I be using as in C# I can do the above as so:

if (origEndDate == origEndDate) { }

and it will come back as true.

Confused!

Thanks for any help!

like image 715
Bex Avatar asked Nov 17 '10 16:11

Bex


People also ask

Can we compare date with Null?

Why or why not? DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type".

How do I assign a null value to a DateTime variable in VB net?

“DateTime is a value type (a structure) and can not be set to null or nothing as with all . Net value types. The default value for a datetime value is zeros for the date portion and 12:00:00 AM for the Time portion.”

Is null less than DateTime?

Any instance of DateTime, regardless of its value, is considered greater than null .

How to check if DateTime is null c#?

Use model. myDate. HasValue. It will return true if date is not null otherwise false.


1 Answers

Try originalDate.Equals(newDate) maybe?

(No, this will not cause an NRE when either date is null, since the variables are actually of the value type Nullable(Of DateTime) and are therefore not actually null until they are boxed.)

like image 67
cdhowie Avatar answered Sep 28 '22 18:09

cdhowie