将 Oracle 日期转换为 c# DateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16596231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:25:14  来源:igfitidea点击:

Convert Oracle Date to c# DateTime

c#datedatetime

提问by Bojan

I am trying to read a record from oracle database of type Date and then convert it to ASP.NET c# DateTime object. Problem is, it picks up the date but not the time. Command I'm using is:

我正在尝试从日期类型的 oracle 数据库中读取记录,然后将其转换为 ASP.NET c# DateTime 对象。问题是,它选择日期而不是时间。我正在使用的命令是:

DateTime dt = Convert.ToDateTime(ds.Tables[0].Rows[0][0].ToString());

If I try to print ds.Tables[0].Rows[0][0].ToString()then it shows the time as well. Anyone know how to get around this?

如果我尝试打印,ds.Tables[0].Rows[0][0].ToString()它也会显示时间。有谁知道如何解决这个问题?

My oracle date field has a value/format of:2013-01-01 14:14:14

我的 oracle 日期字段的值/格式为:2013-01-01 14:14:14

采纳答案by Alexander Bortnik

This:

这个:

DateTime dateTime = DateTime.ParseExact(ds.Tables[0].Rows[0][0].ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

parses using specified format and does not depend on thread culture.

使用指定的格式解析并且不依赖于线程文化。

回答by vc 74

DateTime dt = ds.Tables[0].AsEnumerable().First().Field<DateTime>(0);

should do the job

应该做这份工作

回答by Steve's a D

Any reason you can't just use DateTime.Parse()? Taking in the database value seemed to give the correct output (with the time included which seems to be what you're after)

有什么理由不能使用DateTime.Parse()?接受数据库值似乎给出了正确的输出(包括时间,这似乎是你所追求的)

enter image description here

在此处输入图片说明

回答by Maaark

Everyone else is overcomplicating it.

其他人都把它复杂化了。

Oracle Managed Data Access (which I assume you're using) returns dates as the "OracleDate" type. OracleDate has a property "Value" which is a c# DateTime.

Oracle Managed Data Access(我假设您正在使用)将日期作为“OracleDate”类型返回。OracleDate 有一个属性“Value”,它是 ac# DateTime。

In my case, to get a DateTime from an out parameter (p2 below), I used

就我而言,要从输出参数(下面的 p2)获取 DateTime,我使用了

return ((OracleDate) p2.Value).Value;

For Op's case where the date in question is in a row of the returned dataset, use

对于 Op 的情况,其中有问题的日期在返回数据集的一行中,请使用

DateTime dt = (DateTime) ds.Tables[0].Rows[0][0];

edit: if taking data from a DataRow, for some reason the date will actually be a c# DateTime

编辑:如果从 DataRow 获取数据,由于某种原因,日期实际上是 ac#DateTime