Error converting String in to DateTime format

会有一股神秘感。 提交于 2019-12-13 07:55:46

问题


I am trying to convert the string in to DateTime so it can be inserted in the Ms SQL Database field which is datetime datatype.

public  DateTime ConvertCloseDate(string closeDate)
{
 return DateTime.ParseExact(closeDate,"YYYY-MM-DDThh:mm:ss",null);
}

Here closeDate holds value like 7/14/0016 5:00:00 AM I need to convert in to the datetime format that Ms SQL Database will accept.

With the above code I am getting error like

 String was not recognized as a valid DateTime.

 Exception type: FormatException
 Source: mscorlib
 Target Site: System.DateTime ParseExact(System.String, System.String, System.Globalization.DateTimeFormatInfo, System.Globalization.DateTimeStyles)
 The following is a stack trace that identifies the location where the exception occured

  at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
  at System.Xml.Xsl.CompiledQuery.Script1.ConvertCloseDate(String closeDate)

回答1:


The DateTime class has no format property to it. The second argument in DateTime.ParseExact is the format of the input.

I don't know enough about your input, but my best guess for the format would be M/DD/yyyy h:mm:ss tt

Once you have a DateTime object, you will be fine, SQL Server will accept it.




回答2:


Try to use TryParse to see if it is a valid datetime and if it is MS SQL will accept closedDate string as is.

DateTime warrantyDate;
bool recDate = DateTime.TryParse(closedDate, out warrantyDate);
if(recDate)
{
    //if rec date is true, MS SQL will accept it as datetime
}


来源:https://stackoverflow.com/questions/43261113/error-converting-string-in-to-datetime-format

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