gpt4 book ai didi

MySQL 字符串未转换为 .NET 时间

转载 作者:行者123 更新时间:2023-11-29 11:36:00 25 4
gpt4 key购买 nike

我正在尝试使用 VB.NET 将 MySQL 时间转换为字符串。

    Dim adpt As New MySqlDataAdapter(dbcmdstring, connection)
Dim myDataTable As New DataTable()
adpt.Fill(myDataTable)

DataGridView1.DataSource = myDataTable
DataGridView1.Columns.Remove("ActivityID")
DataGridView1.Columns.Remove("ActivityDate")
DataGridView1.Columns.Remove("UserID")
DataGridView1.Columns(0).HeaderCell.Value = "Name"
DataGridView1.Columns(1).HeaderCell.Value = "Start Time"
DataGridView1.Columns(2).HeaderCell.Value = "End Time"
DataGridView1.Columns.Add("Duration", "Duration")
DataGridView1.RowHeadersVisible = False

Dim duration As New TimeSpan
Dim durationStr As String = ""
Dim i As Integer = 0
For Each row As DataGridViewRow In DataGridView1.Rows
duration = Date.Parse(row.Cells(2).Value.ToString).Subtract(Date.Parse(row.Cells(1).Value.ToString))
durationStr = Math.Round(duration.TotalMinutes).ToString & ":" & Math.Round(duration.TotalSeconds).ToString
row.Cells(3).Value = durationStr
Next

在构造duration变量的过程中解析日期时,会抛出错误:

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplicationSQL.exe

Additional information: Object reference not set to an instance of an object.

我可以成功解析日期并将其显示在消息框中,但无法将其转换为可用的字符串。我也尝试过仅使用时间的 .value。

有什么帮助吗?

最佳答案

有一种更简单的方法来获取持续时间,而且是一种非常非常简单的方法。

部分问题是这样的:我正在尝试使用 VB.NET 将 MySQL 时间转换为字符串。不需要转换为字符串。如果该列实际上是 MySQL 中的 Time() 列,则它有一个 NET 对应列:TimeSpan,并且可以轻松地使用它来通过减法计算差异。

更简单的方法

dtLog.Columns.Add(New DataColumn("Duration", GetType(TimeSpan)))
For Each r As DataRow In dtLog.Rows
r("Duration") = r.Field(Of TimeSpan)("EndTime") - r.Field(Of TimeSpan)("StartTime")
Next

如果您使用数据源,那么通过DataGridView 操作数据很少是一个好主意。注意:不需要任何字符串。

非常非常简单的方法

在SQL中执行操作:

Dim sql = "SELECT ... StartTime, EndTime, TIMEDIFF(EndTime, StartTime) As Duration FROM ActivityLog"

这将在包含结果的 DataTable 中创建一个 Duration 列。同样,如果您不需要某些列,您可以从 SQL 开始时省略它们,而不是删除 DGV 列。

未将对象引用设置为对象的实例。

最后,这个错误可能与 MySQL 到 VB、字符串或 TimeSpans 的转换无关。默认情况下,DGV 在底部有一个额外的行 - 用户开始添加数据的 NewRow - 但所有单元格都没有。所以:

For Each row As DataGridViewRow In DataGridView1.Rows

这将尝试处理 NewRow 并浏览其单元格将产生 NRE。当您切换到数据表时,它消失了,因为它们没有额外的行。不过,您仍然不需要所有这些旋转。

关于MySQL 字符串未转换为 .NET 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36583483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com