string was not recognized as a valid datetime while assigning the value to Nullable DateTime

时光毁灭记忆、已成空白 提交于 2019-12-12 02:57:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!