如何格式化DataGridView中的DateTime列?

usr*_*ΛΩΝ 39 c# data-binding datetime datagridview winforms

我正在使用带有对象数据绑定的DataGridView来显示有关系统中日志记录实体的信息,这些信息是通过SOAP从远程服务检索的.其中一列称为"上次操作",表示实体最后一次记录消息.这是一个System.DateTime价值.当我读取SOAP响应(下面的示例)时,他的时间戳显然包含所有信息,最多包含第二个分数.

<LoggingEntity>
<host>marty86ce</host>
<process>10148</process>
<logger>http_core</logger>
<appName>httpd</appName>
<ffda>true</ffda>
<lastAction>2010-10-27T12:00:19.5117509Z</lastAction>
<lastHeartbeat>0001-01-01T00:00:00</lastHeartbeat>
<channelId>em_9BA2A2B4D0B6E66</channelId>
<ffdaChannelId>em_E7C8D1D4DE8EEB9</ffdaChannelId>
</LoggingEntity>
Run Code Online (Sandbox Code Playgroud)

当我在桌子上显示它时,我可以读取分钟 http://i.stack.imgur.com/dLYBz.png 当我按下刷新按钮时,我使用以下代码进行数据绑定

public void RefreshEntities()
{
    IEntityManagement management = EntityPlugin.GetProxy();
    LoggingEntity[] result = management.FindLoggingEntities(new TemplateQuery { ffdaSpecified = true, ffda = true }); //Remote invocation

    Invoke(new MethodInvoker(delegate { gridEntities.DataSource = result; })); //THIS does the data binding from the array

    Invoke(new MethodInvoker(delegate { btnRefresh.Enabled = true; }));
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何控制数据绑定值的列格式.我认为格式dd/MM/yyyy hh:mm来自我的系统设置.如何以编程方式覆盖格式设置?

先感谢您

用于Logbus-ng开源项目的Subversion(FFDAGui程序)的完整解决方案代码.

Jla*_*Jla 29

您可以设置所需的格式:

dataGridViewCellStyle.Format = "dd/MM/yyyy";
this.date.DefaultCellStyle = dataGridViewCellStyle;
// date being a System.Windows.Forms.DataGridViewTextBoxColumn
Run Code Online (Sandbox Code Playgroud)

  • `dd/MM/yyyy`将日期格式化为`dd-MM-yyyy`.使用`dd'/'MM'/'yyyy`将日期格式化为`dd/MM/yyyy` (4认同)
  • `yourColumn.DefaultCellStyle = new DataGridViewCellStyle {Format ="dd'/'MM'/'yyyy hh:mm:ss"};` (2认同)

Sar*_*avu 28

如果它是一个Windows窗体Datagrid,您可以使用下面的代码格式化列的日期时间

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";
Run Code Online (Sandbox Code Playgroud)

编辑:

除此之外,如果您需要AM/PM格式的日期时间,您可以使用以下代码

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";
Run Code Online (Sandbox Code Playgroud)