[英]string was not recognized as a valid datetime while assigning the value to Nullable DateTime
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 我有一个文本框,将从中以“ MM / dd / yyyy”格式将日期作为字符串发送,当我将该值分配给可为null的datetime属性值时,由于字符串被识别为无效日期时间而导致错误,我正在转换如下所示的字符串也得到相同的错误
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.
请帮助我。
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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.