[c#] DateTime "null" value

I've been searching a lot but couldn't find a solution. How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I guess this is a quite common question, how do you do that?

This question is related to c# datetime null

The answer is


Following way works as well

myClass.PublishDate = toPublish ? DateTime.Now : (DateTime?)null;

Please note that property PublishDate should be DateTime?


It is worth pointing out that, while a DateTime variable cannot be null, it still can be compared to null without a compiler error:

DateTime date;
...
if(date == null) // <-- will never be 'true'
  ...

Just be warned - When using a Nullable its obviously no longer a 'pure' datetime object, as such you cannot access the DateTime members directly. I'll try and explain.

By using Nullable<> you're basically wrapping DateTime in a container (thank you generics) of which is nullable - obviously its purpose. This container has its own properties which you can call that will provide access to the aforementioned DateTime object; after using the correct property - in this case Nullable.Value - you then have access to the standard DateTime members, properties etc.

So - now the issue comes to mind as to the best way to access the DateTime object. There are a few ways, number 1 is by FAR the best and 2 is "dude why".

  1. Using the Nullable.Value property,

    DateTime date = myNullableObject.Value.ToUniversalTime(); //Works

    DateTime date = myNullableObject.ToUniversalTime(); //Not a datetime object, fails

  2. Converting the nullable object to datetime using Convert.ToDateTime(),

    DateTime date = Convert.ToDateTime(myNullableObject).ToUniversalTime(); //works but why...

Although the answer is well documented at this point, I believe the usage of Nullable was probably worth posting about. Sorry if you disagree.

edit: Removed a third option as it was a bit overly specific and case dependent.


I always set the time to DateTime.MinValue. This way I do not get any NullErrorException and I can compare it to a date that I know isn't set.


I'd consider using a nullable types.

DateTime? myDate instead of DateTime myDate.


I'd consider using a nullable types.

DateTime? myDate instead of DateTime myDate.


If you're using .NET 2.0 (or later) you can use the nullable type:

DateTime? dt = null;

or

Nullable<DateTime> dt = null;

then later:

dt = new DateTime();

And you can check the value with:

if (dt.HasValue)
{
  // Do something with dt.Value
}

Or you can use it like:

DateTime dt2 = dt ?? DateTime.MinValue;

You can read more here:
http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx


Following way works as well

myClass.PublishDate = toPublish ? DateTime.Now : (DateTime?)null;

Please note that property PublishDate should be DateTime?


You can use a nullable class.

DateTime? date = new DateTime?();

DateTime? MyDateTime{get;set;}

MyDateTime = (dr["f1"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr["f1"]);

Although everyone has already given you the answer , I'll mention a way which makes it easy to pass a datetime into a function

[ERROR:cannot convert system.datetime? to system.datetime]

DateTime? dt = null;
DateTime dte = Convert.ToDateTime(dt);

Now you may pass dte inside the function without any issues.


If you're using .NET 2.0 (or later) you can use the nullable type:

DateTime? dt = null;

or

Nullable<DateTime> dt = null;

then later:

dt = new DateTime();

And you can check the value with:

if (dt.HasValue)
{
  // Do something with dt.Value
}

Or you can use it like:

DateTime dt2 = dt ?? DateTime.MinValue;

You can read more here:
http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx


You can set the DateTime to Nullable. By default DateTime is not nullable. You can make it nullable in a couple of ways. Using a question mark after the type DateTime? myTime or using the generic style Nullable.

DateTime? nullDate = null;

or

DateTime? nullDate;

I'd consider using a nullable types.

DateTime? myDate instead of DateTime myDate.


You can use a nullable class.

DateTime? date = new DateTime?();

You can use a nullable DateTime for this.

Nullable<DateTime> myDateTime;

or the same thing written like this:

DateTime? myDateTime;

You can use a nullable class.

DateTime? date = new DateTime?();

If you're using .NET 2.0 (or later) you can use the nullable type:

DateTime? dt = null;

or

Nullable<DateTime> dt = null;

then later:

dt = new DateTime();

And you can check the value with:

if (dt.HasValue)
{
  // Do something with dt.Value
}

Or you can use it like:

DateTime dt2 = dt ?? DateTime.MinValue;

You can read more here:
http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx


I'd consider using a nullable types.

DateTime? myDate instead of DateTime myDate.


If you're using .NET 2.0 (or later) you can use the nullable type:

DateTime? dt = null;

or

Nullable<DateTime> dt = null;

then later:

dt = new DateTime();

And you can check the value with:

if (dt.HasValue)
{
  // Do something with dt.Value
}

Or you can use it like:

DateTime dt2 = dt ?? DateTime.MinValue;

You can read more here:
http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx


Just be warned - When using a Nullable its obviously no longer a 'pure' datetime object, as such you cannot access the DateTime members directly. I'll try and explain.

By using Nullable<> you're basically wrapping DateTime in a container (thank you generics) of which is nullable - obviously its purpose. This container has its own properties which you can call that will provide access to the aforementioned DateTime object; after using the correct property - in this case Nullable.Value - you then have access to the standard DateTime members, properties etc.

So - now the issue comes to mind as to the best way to access the DateTime object. There are a few ways, number 1 is by FAR the best and 2 is "dude why".

  1. Using the Nullable.Value property,

    DateTime date = myNullableObject.Value.ToUniversalTime(); //Works

    DateTime date = myNullableObject.ToUniversalTime(); //Not a datetime object, fails

  2. Converting the nullable object to datetime using Convert.ToDateTime(),

    DateTime date = Convert.ToDateTime(myNullableObject).ToUniversalTime(); //works but why...

Although the answer is well documented at this point, I believe the usage of Nullable was probably worth posting about. Sorry if you disagree.

edit: Removed a third option as it was a bit overly specific and case dependent.


You can use a nullable class.

DateTime? date = new DateTime?();

You can set the DateTime to Nullable. By default DateTime is not nullable. You can make it nullable in a couple of ways. Using a question mark after the type DateTime? myTime or using the generic style Nullable.

DateTime? nullDate = null;

or

DateTime? nullDate;

Given the nature of a date/time data type it cannot contain a null value, i.e. it needs to contain a value, it cannot be blank or contain nothing. If you mark a date/time variable as nullable then only can you assign a null value to it. So what you are looking to do is one of two things (there might be more but I can only think of two):

  • Assign a minimum date/time value to your variable if you don't have a value for it. You can assign a maximum date/time value as well - whichever way suits you. Just make sure that you are consistent site-wide when checking your date/time values. Decide on using min or max and stick with it.

  • Mark your date/time variable as nullable. This way you can set your date/time variable to null if you don't have a variable to it.

Let me demonstrate my first point using an example. The DateTime variable type cannot be set to null, it needs a value, in this case I am going to set it to the DateTime's minimum value if there is no value.

My scenario is that I have a BlogPost class. It has many different fields/properties but I chose only to use two for this example. DatePublished is when the post was published to the website and has to contain a date/time value. DateModified is when a post is modified, so it doesn't have to contain a value, but can contain a value.

public class BlogPost : Entity
{
     public DateTime DateModified { get; set; }

     public DateTime DatePublished { get; set; }
}

Using ADO.NET to get the data from the database (assign DateTime.MinValue is there is no value):

BlogPost blogPost = new BlogPost();
blogPost.DateModified = sqlDataReader.IsDBNull(0) ? DateTime.MinValue : sqlDataReader.GetFieldValue<DateTime>(0);
blogPost.DatePublished = sqlDataReader.GetFieldValue<DateTime>(1);

You can accomplish my second point by marking the DateModified field as nullable. Now you can set it to null if there is no value for it:

public DateTime? DateModified { get; set; }

Using ADO.NET to get the data from the database, it will look a bit different to the way it was done above (assigning null instead of DateTime.MinValue):

BlogPost blogPost = new BlogPost();
blogPost.DateModified = sqlDataReader.IsDBNull(0) ? (DateTime?)null : sqlDataReader.GetFieldValue<DateTime>(0);
blogPost.DatePublished = sqlDataReader.GetFieldValue<DateTime>(1);

I hope this helps to clear up any confusion. Given that my response is about 8 years later you are probably an expert C# programmer by now :)


If you are, sometimes, expecting null you could use something like this:

var orderResults = Repository.GetOrders(id, (DateTime?)model.DateFrom, (DateTime?)model.DateTo)

In your repository use null-able datetime.

public Orders[] GetOrders(string id, DateTime? dateFrom, DateTime? dateTo){...}

Although everyone has already given you the answer , I'll mention a way which makes it easy to pass a datetime into a function

[ERROR:cannot convert system.datetime? to system.datetime]

DateTime? dt = null;
DateTime dte = Convert.ToDateTime(dt);

Now you may pass dte inside the function without any issues.


I always set the time to DateTime.MinValue. This way I do not get any NullErrorException and I can compare it to a date that I know isn't set.


If you are, sometimes, expecting null you could use something like this:

var orderResults = Repository.GetOrders(id, (DateTime?)model.DateFrom, (DateTime?)model.DateTo)

In your repository use null-able datetime.

public Orders[] GetOrders(string id, DateTime? dateFrom, DateTime? dateTo){...}

Given the nature of a date/time data type it cannot contain a null value, i.e. it needs to contain a value, it cannot be blank or contain nothing. If you mark a date/time variable as nullable then only can you assign a null value to it. So what you are looking to do is one of two things (there might be more but I can only think of two):

  • Assign a minimum date/time value to your variable if you don't have a value for it. You can assign a maximum date/time value as well - whichever way suits you. Just make sure that you are consistent site-wide when checking your date/time values. Decide on using min or max and stick with it.

  • Mark your date/time variable as nullable. This way you can set your date/time variable to null if you don't have a variable to it.

Let me demonstrate my first point using an example. The DateTime variable type cannot be set to null, it needs a value, in this case I am going to set it to the DateTime's minimum value if there is no value.

My scenario is that I have a BlogPost class. It has many different fields/properties but I chose only to use two for this example. DatePublished is when the post was published to the website and has to contain a date/time value. DateModified is when a post is modified, so it doesn't have to contain a value, but can contain a value.

public class BlogPost : Entity
{
     public DateTime DateModified { get; set; }

     public DateTime DatePublished { get; set; }
}

Using ADO.NET to get the data from the database (assign DateTime.MinValue is there is no value):

BlogPost blogPost = new BlogPost();
blogPost.DateModified = sqlDataReader.IsDBNull(0) ? DateTime.MinValue : sqlDataReader.GetFieldValue<DateTime>(0);
blogPost.DatePublished = sqlDataReader.GetFieldValue<DateTime>(1);

You can accomplish my second point by marking the DateModified field as nullable. Now you can set it to null if there is no value for it:

public DateTime? DateModified { get; set; }

Using ADO.NET to get the data from the database, it will look a bit different to the way it was done above (assigning null instead of DateTime.MinValue):

BlogPost blogPost = new BlogPost();
blogPost.DateModified = sqlDataReader.IsDBNull(0) ? (DateTime?)null : sqlDataReader.GetFieldValue<DateTime>(0);
blogPost.DatePublished = sqlDataReader.GetFieldValue<DateTime>(1);

I hope this helps to clear up any confusion. Given that my response is about 8 years later you are probably an expert C# programmer by now :)


I had the same problem as I had to give Null as a parameter for DateTime while performing Unit test for Throws ArgumentNullException.It worked in my case using the following option:

Assert.Throws<ArgumentNullException>(()=>sut.StartingDate = DateTime.Parse(null));

You can use a nullable DateTime for this.

Nullable<DateTime> myDateTime;

or the same thing written like this:

DateTime? myDateTime;

I had the same problem as I had to give Null as a parameter for DateTime while performing Unit test for Throws ArgumentNullException.It worked in my case using the following option:

Assert.Throws<ArgumentNullException>(()=>sut.StartingDate = DateTime.Parse(null));

It is worth pointing out that, while a DateTime variable cannot be null, it still can be compared to null without a compiler error:

DateTime date;
...
if(date == null) // <-- will never be 'true'
  ...

I always set the time to DateTime.MinValue. This way I do not get any NullErrorException and I can compare it to a date that I know isn't set.


You can set the DateTime to Nullable. By default DateTime is not nullable. You can make it nullable in a couple of ways. Using a question mark after the type DateTime? myTime or using the generic style Nullable.

DateTime? nullDate = null;

or

DateTime? nullDate;

DateTime? MyDateTime{get;set;}

MyDateTime = (dr["f1"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr["f1"]);

You can use a nullable DateTime for this.

Nullable<DateTime> myDateTime;

or the same thing written like this:

DateTime? myDateTime;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"