Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert to DateTime but have default value if input is blank?

What .NET function will convert to a DateTime but have a default value if input is blank?

eg.

DateTime dtTest = Convert.ToDateTime(getDateString());

If getDateString() returns an empty string Convert.ToDateTime throws an exception.

How can I instead have a default value of "9:00AM" used instead of the empty string? Is this something where TryParse could be used?

like image 227
CJ7 Avatar asked Feb 12 '13 07:02

CJ7


People also ask

How can I pass an empty string value to a date field in Java?

Try setting the value of the date to 0000-00-00, this usually works (never tried it in this scenario but everywhere else it always worked for me).

Can DateTime be null?

DateTime itself is a value type. It cannot be null.

How do I only display date from DateTime?

ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.


2 Answers

Use DateTime.TryParse and if the parsing fails you can assign DateTime.MinValue.AddHours(9) to get (9:00AM) time with Minimum Date.

string str = "";
DateTime temp;
DateTime dt = DateTime.TryParse(str, out temp) ? temp : DateTime.MinValue.AddHours(9);

For the above code your dt object will hold {01/01/0001 9:00:00 AM}

like image 119
Habib Avatar answered Oct 27 '22 14:10

Habib


I have used something called a ternary statement. You can view an example here: MSDN

    string myDate = getDateString();
    DateTime dtTest = Convert.ToDateTime(String.IsNullOrEmpty(myDate) ? "my default value" : myDate);

The ternary statement is below:

String.IsNullOrEmpty(myDate) ? "my default value" : myDate

And it can be read as follows:

If the string is null or empty, then use "my default value", otherwise use myDate.

like image 29
Robert Avatar answered Oct 27 '22 14:10

Robert