In VB.NET, is there a way to set a DateTime
variable to "not set"? And why is it possible to set a DateTime
to Nothing
, but not possible to check if it is Nothing
? For example:
Dim d As DateTime = Nothing Dim boolNotSet As Boolean = d Is Nothing
The second statement throws this error:
'Is' operator does not accept operands of type 'Date'. Operands must be reference or nullable types.
Use model. myDate. HasValue. It will return true if date is not null otherwise false.
Use the value property to check if an input type="date" is empty, e.g. if (! dateInput. value) {} . The value property stores the date formatted as YYYY-MM-DD or has an empty value if the user hasn't selected a date.
DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.
SELECT * FROM employe WHERE date IS NOT NULL AND (date > ? AND date < ?) We first check if the date is null. If this condition its true, then it will check if the date is inside the range.
This is one of the biggest sources of confusion with VB.Net, IMO.
Nothing
in VB.Net is the equivalent of default(T)
in C#: the default value for the given type.
0
for Integer
, False
for Boolean
, DateTime.MinValue
for DateTime
, ... null
value (a reference that refers to, well, nothing).The statement d Is Nothing
is therefore equivalent to d Is DateTime.MinValue
, which obviously does not compile.
Solutions: as others have said
DateTime?
(i.e. Nullable(Of DateTime)
). This is my preferred solution.d = DateTime.MinValue
or equivalently d = Nothing
In the context of the original code, you could use:
Dim d As DateTime? = Nothing Dim boolNotSet As Boolean = d.HasValue
A more comprehensive explanation can be found on Anthony D. Green's blog
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With