Set an empty DateTime variable

2020-02-26 13:47发布

I would declare an empty String variable like this:

    string myString = string.Empty;

Is there an equivalent for a 'DateTime' variable ?

Update :

The problem is I use this 'DateTime' as a parameter for a 'StoredProcedure' in SQL. E.g:

    DateTime? someDate = null;
    myCommand.Parameters.AddWithValue("@SurgeryDate", someDate);

When I run this code an exception is catched telling me the 'StoredProcedure' expected a '@SurgeryDate' parameter. But i provided it. Any idea why?

标签: c# sql datetime
12条回答
再贱就再见
2楼-- · 2020-02-26 14:29

You may want to use a nullable datetime. Datetime? someDate = null;

You may find instances of people using DateTime.Max or DateTime.Min in such instances, but I highly doubt you want to do that. It leads to bugs with edge cases, code that's harder to read, etc.

查看更多
狗以群分
3楼-- · 2020-02-26 14:29

Either:

DateTime dt = new DateTime();

or

DateTime dt = default(DateTime);
查看更多
趁早两清
4楼-- · 2020-02-26 14:35

No. You have 2 options:

DateTime date = DateTime.MinValue;

This works when you need to do something every X amount of time (since you will always be over MinValue) but can actually cause subtle errors (such as using some operators w/o first checking if you are not MinValue) if you are not careful.

And you can use Nullable:

DateTime? date = null;

Which is nice and avoids most issues while introducing only 1 or 2.

It really depends on what you are trying to achieve.

查看更多
手持菜刀,她持情操
5楼-- · 2020-02-26 14:35

You can set a DateTime variable to be '1/1/0001 00:00:00' but the variable itself cannot be null. To get this MinTime use:

DateTime variableName = DateTime.MinValue;
查看更多
地球回转人心会变
6楼-- · 2020-02-26 14:36

There's no such thing as an empty date per se, do you mean something like:

DateTime? myDateTime = null;
查看更多
干净又极端
7楼-- · 2020-02-26 14:37

A string is a sequence of characters. So it makes sense to have an empty string, which is just an empty sequence of characters.

But DateTime is just a single value, so it's doesn't make sense to talk about an “empty” DateTime.

If you want to represent the concept of “no value”, that's represented as null in .Net. And if you want to use that with value types, you need to explicitly make them nullable. That means either using Nullable<DateTime>, or the equivalent DateTime?.

DateTime (just like all value types) also has a default value, that's assigned to uninitialized fields and you can also get it by new DateTime() or default(DateTime). But you probably don't want to use it, since it represents valid date: 1.1.0001 0:00:00.

查看更多
登录 后发表回答