0

i am fetching the date by below code from db using c# ,how to check null date .when date is null then it shows default date on page 01/01/0001

IssueDate = dataReader.GetValue<DateTime>(DbColumnNames.PLAST_ISSUE_DT)
vim
  • 824
  • 3
  • 12
  • 27

2 Answers2

3

DateTime is not a refence type, so it cannot be null. You can use a nullable date with DateTime? (which is the same as Nullable<DateTime>) to check for null value.

DateTime? issueDate = dataReader.GetValue<DateTime?>(DbColumnNames.PLAST_ISSUE_DT);

if (issueDate == null) {
    // Is null
}

Or check for the default value of DateTime, which should be 01/01/0001.

DateTime issueDate = dataReader.GetValue<DateTime>(DbColumnNames.PLAST_ISSUE_DT);

if (issueDate == default) {
    // Is default value
}
Jossean Yamil
  • 850
  • 2
  • 9
  • 22
  • 2
    `DateTime is not a refence type, so it cannot be null.` A minor quibble, but `DateTime?` is _also_ not a reference type (which is why I wouldn't mention that explicitly - it just confuses the issue). Perhaps it would be clearer to say that `DateTime` cannot have the value `null`? – mjwills Jun 03 '21 at 22:26
  • @mjwills I never said that `DateTime?` is a reference type. – Jossean Yamil Mar 25 '22 at 21:45
  • You never _said_ it, but your argument strongly _implies_ it. You say "X is not Y, you need to use Z instead". At the very least you _imply_ that Z is Y (which, in this case, it isn't) - hence why I said it was best not to argue it in that way. In other words, by saying "DateTime is not a refence type, so it cannot be null" it introduces confusion - since you are suggesting using `DateTime?` which _also_ is not a reference type. So the person reading the answer will be confused. Why does `DateTime?` work even if it isn't a reference type? Hence why I suggested the specific wording that I did. – mjwills Mar 27 '22 at 01:53
1

DateTime is a value type so it always evaluates to something. Likewise, if you don't put a value in an int the value inside will be 0 and not null.

If you do want to have null then you have to make your database field nullable and use a define IssueDate as type DateTime? which is Nullable of DateTime and it will be able to hold the null value.

Fabulous
  • 2,393
  • 2
  • 20
  • 27