Working with a DateTime Zero

I am using LINQ and have several thats DateTime properties? a type.

If now I want to add a value from a text field, I cannot get it to work.

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ScoringLastUpgrade", DbType="Date")] public System.Nullable<System.DateTime> ScoringLastUpgrade 

In the text box that I use, I made sure that with javascript the format would be '2011-06-17'

But now when I try to do this:

 myObject.ScoringLastUpgrade = Convert.ToDateTime(txtScoringUpgradeDate.Text).ToShortDateString(); 

I get this error: "Can't convert type string to DateTime?"

How to do it?

+4
source share
4 answers

Do not convert it to string using 'ToShortDateTimeString', just set the result to Convert.ToDateTime :

 myObject.ScoringLastUpgrade = Convert.ToDateTime(txtScoringUpgradeDate.Text); 

Assuming you have done a sufficient check on txtScoringUpgradeDate.Text ?

My preference when working with these type conversions is to use the TryParse method, for example:

 DateTime date; if (DateTime.TryParse(txtScoringUpgradeDate.Text, out date)) myObject.ScoringLastUpgrade = date; 

Convert.ToDateTime , just like an explicit DateTime.Parse will InvalidCastException when an InvalidCastException value occurs. It is better to make a tollerant error code, then the needles catch an exception.

UPDATE : based on the last comment:

You should not return DateTime.MinValue in this case, since MinValue less than the supported minimum value of the datetime column. CLR datetime supports a date range up to 0000-01-01, while SQL datetime (as well as the comparative CLR type SqlDateTime ) supports a minimum value of 1753-01-01. Since this is a value with a datetime value of zero, you must set it to null:

 public static DateTime? ToNullableDateTime(this string date) { DateTime dateTime; return (DateTime.TryParse(date, out dateTime)) ? (DateTime?)dateTime : null; } 
+2
source

Calling .ToShortDateString() converts it to a string. You must delete this call.

Also, you say you are convinced of the format with javascript. What if the user does not have javascript, you should also do server side checks. Also, since it is in a specific format, you can use DateTime.ParseExact or DateTime.TryParseExact (so an invalid format does not throw an exception), since it is more efficient. (The format string will be "yyyy-MM-dd" ), I suppose.

+3
source

The problem is that you put ToShortDateString() at the end there, converting the DateTime back to string again. Try deleting this part of the line.

0
source

In my case (.cshtml):

 <td>@item.InvoiceDate.Value.ToShortDateString().ToString()</td> 

Where InvoiceDtae is a Nullable Date in DB

0
source

All Articles