Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set DateTime to null

Using C#. I have a string dateTimeEnd.

If the string is in right format, I wish to generate a DateTime and assign it to eventCustom.DateTimeEnd of type

public Nullable<System.DateTime> DateTimeEnd { get; set; } 

If dateTimeEnd is null or empty I need eventCustom.DateTimeEnd set to null.

I am trying to achieve this using the following code but I get always null for eventCustom.DateTimeEnd.

Could you please help me out to define what is wrong in my code?

   DateTime? dateTimeEndResult;      if (!string.IsNullOrWhiteSpace(dateTimeEnd))         dateTimeEndResult = DateTime.Parse(dateTimeEnd);   eventCustom.DateTimeEnd = dateTimeEndResult = true ? (DateTime?)null : dateTimeEndResult; 
like image 512
GibboK Avatar asked May 27 '13 08:05

GibboK


People also ask

Can DateTime be set to null?

Is it possible to set datetime object to null in C#? DateTime is a Value Type like int, double etc. so there is no way to assigned a null value.

How do I pass DateTime null in SQL?

In SQL Server just insert NULL in the Datetime column: INSERT INTO Table(name, datetimeColumn, ...) VALUES('foo bar', NULL, ..);

Can date data type be null?

Yes, that works fine.

Can we assign null to DateTime in C#?

CSharp Online TrainingUsing the DateTime nullable type, you can assign the null literal to the DateTime type. A nullable DateTime is specified using the following question mark syntax.


1 Answers

It looks like you just want:

eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)     ? (DateTime?) null     : DateTime.Parse(dateTimeEnd); 

Note that this will throw an exception if dateTimeEnd isn't a valid date.

An alternative would be:

DateTime validValue; eventCustom.DateTimeEnd = DateTime.TryParse(dateTimeEnd, out validValue)     ? validValue     : (DateTime?) null; 

That will now set the result to null if dateTimeEnd isn't valid. Note that TryParse handles null as an input with no problems.

like image 100
Jon Skeet Avatar answered Oct 22 '22 00:10

Jon Skeet