问题
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