[英]DataTable not showing minutes and seconds
string command = "select x,y,z,t,ModifiedDate " +
" from ZZ where PP='" + XX + "' and Type='" + YY + "' order by ModifiedDate";
connection();
SqlCommand command = new SqlCommand(command, con);
command.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
ModifiedDate是一个DateTime - 在SQL中我看到"2019-07-23 12:02:35.283"
但是当我想在C#中看到“dt”时,我只能看到"2019-07-23"
我怎样才能看到分钟和秒钟的全职?
DataTable
列的类型是DateTime
。 ZZ
是一张桌子。
您可以尝试将行设置为以下内容:
((DateTime)row[0]).ToString("yyyy-MM-dd HH:mm:ss")
就像你在评论中所说的那样,只需在分配给变量时将格式添加到ToString()。
您所拥有的甚至不应该编译,因为您不能在同一范围内声明具有相同名称的string
和SqlCommand
对象。 像这样运行查询:
string sql = @"
select x,y,z,t,ModifiedDate
from ZZ
where PP= @XX and Type= @YY
order by ModifiedDate";
DataTable dt = new DataTable();
// .Net connection pooling means you really do want a new connection object most of the time. Don't try to re-use it!
// The "using" blocks make sure your objects are closed and disposed, even if an exception is thrown
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{
//use the actual column types and lengths from your database here
cmd.Parameters.Add("@XX", SqlDbType.NVarChar, 30).Value = XX;
cmd.Parameters.Add("@YY", SqlDbType.NVarChar, 10).Value = YY;
da.Fill(dt);
}
但这仍然无法解决所有问题。 它主要是关闭原始代码中的巨大的广泛安全漏洞和潜在的拒绝服务问题。
该问题的实际问题与此代码不同。 你的时间部分ModifiedDate
列于结果DataTable中。 真。 我承诺。 如果您没有看到它,那是因为您尝试观察或显示这些结果时的DataView,格式字符串或其他问题。
C#中没有Date
类 - 甚至DateTime.Date()
返回另一个带有全零时间组件的DateTime
对象。
您的问题听起来非常像区域设置问题,或更具体地说,C#中的CultureInfo
。 您的默认(或由Thread.CurrentThread
的CurrentCulture
或CurrentUICulture
应用的“当前”)具有CultureInfo.DateTimeFormat
设置,以提供无日期格式的日期。
可能FullDateTimePattern
设置为"yyyy-mm-dd"
或等效的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.