将String转换为DateTime格式时出错 [英] Error converting String in to DateTime format

查看:138
本文介绍了将String转换为DateTime格式时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串转换为DateTime,以便可以将其插入Ms SQL Database字段(即datetime数据类型)中.

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);
}

在这里closeDate保留着7/14/0016 5:00:00 AM这样的值,我需要将其转换为SQL数据库女士将接受的日期时间格式.

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)

推荐答案

DateTime类没有格式属性. DateTime.ParseExact中的第二个参数是 input 的格式.

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

我对您的输入了解不多,但我对格式的最佳猜测是 M/DD/yyyy h:mm:ss tt

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

一旦有了DateTime对象,就可以了,SQL Server会接受它.

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

这篇关于将String转换为DateTime格式时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆