我正在尝试将字符串转换为DateTime,以便可以将其插入Ms SQL数据库字段,即datetime数据类型。
public DateTime ConvertCloseDate(string closeDate)
{
return DateTime.ParseExact(closeDate,"YYYY-MM-DDThh:mm:ss",null);
}
这里closeDate保存的值类似于7/14/0016 5:00:00 AM我需要转换为Ms SQL Database将接受的日期时间格式。
使用上面的代码我收到错误
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)
答案 0 :(得分:0)
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.
答案 1 :(得分:-1)
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
}