使用c#

时间:2017-09-13 11:00:32

标签: c# sql-server datetime

在我的产品日期中,将商店存储为数据库中的规范SQL日期。 2011-10-24 00:00:00.000

我的应用程序默认日期文化从客户更改为客户 我想解析日期。我该怎么办?

我目前使用(System.DateTime)"2011-10-24 00:00:00.000"并且在大多数机器上这都可以正常工作,我知道有些机器会得到InvalidCastException

我真的想使用DateTime.ParseExact并传递format作为参数,但我无法在格式列表中找到它。

System.DateTime.ParseExact("2011-10-24 00:00:00.000", "<The format string>");

编辑:

完整代码

DataTable table= GetDataTable();
Datetime date = (System.DateTime)table["DateCulomnName"];// Here is where the exception may be thrown

1 个答案:

答案 0 :(得分:3)

如果数据库已将列作为DateTime,则无需将其转换为字符串,以便将其转换为DateTime变量。

可以直接从DateTime分配到DataRow字段。换句话说,从DataRow字段到DateTime,你需要一个类型转换。像这样:

DataTable t = new DataTable();
t.Columns.Add("DATE", typeof(DateTime));

DataRow r = t.NewRow();
r["DATE"] = DateTime.Now;

DateTime fromRow = (DateTime)r["DATE"];

无论CurrentCulture如何,这都可以。

将DateTime作为字符串,只应在实际想要在UI或日志文件中显示时使用。