【问题标题】:How to show only month and year of date in DataColumn of Datatable?如何在 Datatable 的 DataColumn 中仅显示日期的月份和年份?
【发布时间】:2015-05-22 02:50:04
【问题描述】:

我在 C# windows 应用程序中填充了一个 DataGridView。我有一个 DataTable,我在其中显示从数据库中检索的日期。我的问题是,我从数据库中获取的日期也包括时间信息。例如:2003 年 1 月 12:00:00 AM。

我只想在数据表的单元格中显示该日期的年份和月份(2003 年 1 月)部分。我试图改变当前线程的文化信息,但没有奏效。有没有其他方法可以做到这一点?

我使用 MySQL 作为我的数据库,并且我已将此列的数据类型设置为 DATE,但我仍然得到这个时间信息。谁能解释一下 MySQL 的这种行为?

【问题讨论】:

  • 如何填充 DataGridView?
  • 通过将datagridview的datasource属性设置为datatable
  • 好吧,也许我理解错了。但是,如果您将 DataGridView 的数据源绑定到 DataTable(来自 DB),并且您正在显示此信息 - 您不能在 DataGridView 的 BoundColumn/TemplateColumn 上使用 DataFormatString 吗?这意味着您将日期从 MySql 抽象到 DT,然后抽象到处理化妆品的 DGV...
  • ^^ 刚刚读到:“windows 应用程序”,请忽略我最后的评论...

标签: c# mysql c#-2.0


【解决方案1】:

将列上的Format 属性设置为the Month/Year format specifier

// Set the Format property on the "Last Prepared" column to cause
// the DateTime to be formatted as "Month, Year".
dataGridView1.Columns["Last Prepared"].DefaultCellStyle.Format = "y";

【讨论】:

  • 很好的答案。我知道这已经过时了,但我想添加具有所有日期/时间格式的 this 参考。
【解决方案2】:

如果您更喜欢在 SQL 级别执行此操作,您可以在您的选择中执行此操作;

select convert(varchar(max),getdate(),107) as thedate

我总是建议不要抽象数据,而是让 datagridview 做修饰。

【讨论】:

    【解决方案3】:

    谢谢大家。 我通过更改查询解决了我的问题。我使用了 MySql 的 date_format() 函数,它给了我精确的格式。 这是提供有关此功能的更多信息的链接。

    http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 2012-02-22
      • 1970-01-01
      • 2012-01-26
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      相关资源
      最近更新 更多