【问题标题】:How can I store a formatted DateTime into column of type DateTime in Database?如何将格式化的 DateTime 存储到数据库中 DateTime 类型的列中?
【发布时间】:2019-06-02 04:12:03
【问题描述】:

我正在从数据集中的数据库中检索数据并将其打印到 pdf 文档中。一个表有一个 DateTime 列,其值为"12/27/2018 12:00:00 AM"。我正在尝试将其格式化为 dd/MM/yyyy 但没有成功,因为它期望 DateTime 并且格式化返回一个字符串值。我应该更改列数据类型还是有办法维护它并格式化日期时间?

【问题讨论】:

  • " but with no success" 是什么意思,遇到什么错误,求个码sn-p
  • 您不能直接格式化 DateTime,但是您可以格式化它的显示方式。我不是 WinForms 甚至不是 DataTable 专家,但我很确定您可以为 DateTime 列指定格式。 stackoverflow.com/q/40947319/9363973 也可能重复
  • 格式化不是数据层的责任,但应该只在 UI 中完成。
  • 您不能将格式设置为数据集中的日期时间字段。当您在用户界面上显示此数据时会应用格式设置。您使用的是哪种 ui 控件(DataGridView、Label、...)?

标签: c# datetime pdf-generation console-application datetime-format


【解决方案1】:

我建议将数据库从字符串更改为日期时间。但如果你不能,你可以使用这样的东西

            DataTable dt1 = new DataTable();
            DataTable dt2 = dt1.Clone();

            //change columns type
            dt2.Columns["Col A"].DataType = typeof(DateTime);
            int colNumber = dt2.Columns.IndexOf("Col A");

            foreach (DataRow row in dt1.AsEnumerable())
            {
                object[] rowData = row.ItemArray;
                rowData[colNumber] = DateTime.Parse(row.Field<string>("Col A"));
                dt2.Rows.Add(rowData);
            }

【讨论】:

  • 谢谢,这样就可以了,克隆并更改该列的数据类型,最后再次填充它。
猜你喜欢
  • 1970-01-01
  • 2015-12-14
  • 2021-01-01
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
相关资源
最近更新 更多