开发者

Working with nullable DateTime

开发者 https://www.devze.com 2023-03-13 11:11 出处:网络
I am using LINQ and have a few properties thats DateTime? type. If i now want to add the value from a textbox i cant seem to get this to work.

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

If i now want to add the value from a textbox i cant seem to get this to work.

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

The textbox i use i have made sure with javascript that the format will be '2011-06-17'

But now when i try to do this:

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

I get this error: "Cannot convert type string to开发者_Go百科 DateTime?"

How to do this?


The .ToShortDateString() call is converting it into a string. You should remove that call.

Also, you say you've made sure of the format with javascript. What if the user doesn't have javascript, you should do server-side checks too. Also, since it's in a given format, you can use DateTime.ParseExact or DateTime.TryParseExact (so an invalid format doesn't throw an exception) since its more efficient. (The format string would be "yyyy-MM-dd") i believe.


Don't convert it to string using 'ToShortDateTimeString', just set the result of Convert.ToDateTime:

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

Assuming you've done sufficient validation on txtScoringUpgradeDate.Text?

My preference when dealing with these type conversions is to use the TryParse method, e.g.:

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

The Convert.ToDateTime, much like the explicit DateTime.Parse will throw an InvalidCastException when an excepional value occurs. It's better to make your code fault tollerant then needlesly catch an exception.

UPDATE: based on your last comment:

You shouldn't return DateTime.MinValue in this case, as MinValue is less than the supported min value of a datetime column. the CLR DateTime supports a date range down to 0000-01-01, whereas the SQL datetime (as well as the comparative CLR SqlDateTime type) supports a minimum value of 1753-01-01. As it as a nullable DateTime, you should set it to null:

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


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


In my case (.cshtml):

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

Where InvoiceDtae is Nullable Date in DB

0

精彩评论

暂无评论...
验证码 换一张
取 消