问题
I have a textbox from which I am sending date as string in 'MM/dd/yyyy' formate, and when I am assigning that value to nullable datetime property value getting the error as string was not recognized as a valid datetime, I am converting the string as below then also getting the same error
private Tbl_UserDetails GetAnnouncementInformation(Tbl_UserDetails userDetails, Dictionary<string, object> details)
{
userDetails.JoiningDate = string.IsNullOrEmpty(details["JoiningDate "].ToString()) ?
(DateTime?)null :
DateTime.ParseExact(details["JoiningDate "].ToString(),
"MM/dd/yyyy", null);
userDetails.JoiningDate = string.IsNullOrEmpty(details["JoiningDate "].ToString()) ?
(DateTime?)null :
DateTime.ParseExact(details["JoiningDate "].ToString(),
"MM/dd/yyyy", CultureInfo.InvariantCulture);
}
In both the way I am getting the same error. Please help me in this.
回答1:
You could do:
DateTime tempDate;
userDetails.JoiningDate = DateTime.TryParseExact(
details["JoiningDate "].ToString(),
"MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out tempDate)
? tempDate
: (DateTime?)null;
With extention of :
public static class MyExtensions
{
public static DateTime? GetNullableDateTime(
this String str, string format = "MM/dd/yyyy")
{
DateTime tempDate;
var result = DateTime.TryParseExact(str, format,
CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDate)
? tempDate
: default(DateTime?);
return result;
}
}
It would look like:
userDetails.JoiningDate =
details["JoiningDate "].ToString().GetNullableDateTime();
Example program
Assert.IsNull("sddfsdf".GetNullableDateTime());
Assert.IsNotNull("10/20/2014".GetNullableDateTime());
Assert.IsNotNull("20.10.2014".GetNullableDateTime("dd.MM.yyyy"));
来源:https://stackoverflow.com/questions/25480733/string-was-not-recognized-as-a-valid-datetime-while-assigning-the-value-to-nulla