Reader.GetValue 日期值

Reader.GetValue date value

我正在从 SQL 服务器数据库中循环出 reader.GetValue,一切正常,但是我在 table 中有一个数据类型为 Date 的列。当我查看 table 中的数据时,它正确显示了没有时间的日期“18-Dec-17”。

reader 的输出格式如下:'18-Dec-17 12:00:00 AM' 并且所有记录显示 12:00:00 AM 相同,无论日期更改如何.

有人可以让我知道这里发生了什么吗?是否有删除的选项,或者我是否需要正则表达式或替换它?

while (reader.Read())
{
    while (cnt_field <= reader.FieldCount - 1)
    {
        db_output = db_output + "" + reader.GetValue(cnt_field) + " -\t ";
        cnt_field++;
    }//WEND
    cnt_field = 0;
    db_output = db_output + "\n\r";
}//WEND

reader.GetValue(cnt_field) 的调用正在返回表示日期的 DateTime("boxed" 作为 object)。现在;在数据库和 DateTime 中,日期时间值 没有格式 - 它们只是 date/time 的原始数值。当你 concatenate this 与一个字符串时,默认的 .ToString() 被使用,它应用你当前的文化和默认格式说明符。所以:如果 不是您的意图:您需要告诉它您的意图:

var when = (DateTime)reader.GetValue(cnt_field);
db_output = db_output + "" + when.ToString(chosenFormat) + " -\t ";

您可能还想明确指定一种区域性 - CultureInfo.InvariantCulture 通常是日志记录等的不错选择。

您可以选择standard format specifiers or custom format specifiers来构建您想要的格式。您可能需要 "dd-MMM-yy",因此:

db_output = db_output + "" + when.ToString("dd-MMM-yy") + " -\t ";

对于 "" + reader.GetValue(...),您正在执行隐式 reader.GetValue(...).ToString()

然后您看到的是 DateTime 的默认表示。 dotNET 没有单独的 Date 类型。

因此您必须检测循环内的 DateTime 值并应用所需的格式。

类似于

while (cnt_field <= reader.FieldCount - 1)
{
   object value = reader.GetValue(cnt_field);
   if (value is DateTime)
     db_output += ((DateTime)value).ToShortDateString();  // apply a std/custom Date format
   else   
      db_output += value.ToString(); 

   db_output += " -\t ";
   ....
}