You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历DataTable将DateTime值更新为Date格式的正确语法是什么

核心问题原因

  • 如果你的DataColumn的DataType原本就是DateTime类型,存储的是纯日期数值,本身不存在「格式」属性,你把格式化后的字符串赋值回去时,DataTable会自动将字符串隐式转换回DateTime对象,自然看不到格式变化。
  • 原有代码冗余:DateTime.TryParse已经将解析成功的日期写入了cellDate变量,不需要再调用CDate(row(dc))重复解析。

推荐方案(无需修改数据源)

如果只是需要在界面显示时用dd/MM/yyyy格式,不需要修改DataTable本身的存储值,直接在绑定控件处设置格式即可,保留DateTime类型的排序、计算等原生能力。
比如绑定到DataGridView时,对应列设置:

DataGridView1.Columns("你的日期列名").DefaultCellStyle.Format = "dd/MM/yyyy"

方案2:确实需要将格式化后的日期作为字符串存入DataTable

如果业务要求必须把字符串格式的日期存在DataTable里,需要先调整列的类型为String,或者新增字符串类型列存储结果,修正后的代码分两种场景:

场景A:修改原有日期列(需先处理数据再改类型,避免丢失)

Dim dt As DataTable
' 新增临时字符串列存格式化结果
dt.Columns.Add("TempDateCol", GetType(String))
Dim cellDate = DateTime.MinValue

For Each row As DataRow In dt.Rows
    For Each dc As DataColumn In dt.Columns
        ' 仅处理DateTime类型的列
        If dc.DataType Is GetType(Date) AndAlso row(dc) IsNot DBNull.Value Then
            If DateTime.TryParse(row(dc).ToString(), cellDate) Then
                row("TempDateCol") = cellDate.ToString("dd/MM/yyyy")
            End If
        End If
    Next
Next

' 删除原有日期列,将临时列重命名为原列名
dt.Columns.Remove("你的原有日期列名")
dt.Columns("TempDateCol").ColumnName = "你的原有日期列名"

场景B:原有日期列本身就是String类型

直接修正原有逻辑的冗余部分即可生效:

Dim dt As DataTable
Dim cellDate = DateTime.MinValue
For Each row As DataRow In dt.Rows
    For Each dc As DataColumn In dt.Columns
        dc.ReadOnly = False
        If row(dc) IsNot DBNull.Value Then
            If DateTime.TryParse(row(dc).ToString(), cellDate) Then
                ' 直接用已经解析好的cellDate格式化,不需要二次转换
                row(dc) = cellDate.ToString("dd/MM/yyyy")
            End If
        End If
    Next
Next

内容的提问来源于stack exchange,提问作者stonypaul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 10:21:02