我从 mysql 中检索了两个日期时间变量。 一个等于“now()”,另一个代表最后一次更改行的时间。
我需要比较这两个日期时间值以获得两者之间的差异。
这就是我正在尝试的(我从 Mysql 中读取的内容由定制的 web api 处理)...
'get the current time
Dim nowtime As DateTime = readsql("now()", "hosts", "")
Console.WriteLine("NOW IS : " & nowtime)
'read in all the rows
Dim hosts() As String = readsql("hostname", "hosts", "chk_ping=1").ToString.Split("|")
For Each host As String In hosts
If Not host.Contains("No results found") Then
Dim thishostip As String = readsql("IP", "hosts", "hostname='" & host & "'")
Dim thishostlastpoll As DateTime = readsql("last_poll", "hosts", "hostname='" & host & "'")
If thishostip.Contains("No results found") Then Exit For
Console.WriteLine("HOST TIME IS:" & thishostlastpoll.ToString)
Dim timedifference As Integer = DateTime.Compare(nowtime, thishostlastpoll)
Console.WriteLine("Time diff for " & host & " is : " & timedifference)
End If
Next
我的日期时间值是这样的...
18/01/2016 10:53:00
18/01/2016 10:52:52
并且不会抛出任何错误/异常,但无论差异如何,'timedifference' 永远都是 1。
我怀疑它与日期时间的格式有关,而不是 VB 想要的格式,但我找不到任何将 mysql 转换为 vb 日期时间的方法,恰恰相反。
任何方向都将得到应用!提前致谢!
最佳答案
我怀疑它与日期时间的格式有关,而不是 VB 想要的格式,但我找不到任何将 mysql 转换为 vb 日期时间的方法,恰恰相反。
您可能会对一两件事感到困惑。
首先,日期没有格式。格式是计算机(或您编写的计算机代码)向用户显示日期的方式。 Net(不是 VB 本身)DateTime
是一个指示存储为非常大数字的时间点的值。由于 635886720000000000
(今天的日期)对我们大多数人来说意义不大,DateTime
类型以常规范式表示它。
MySql
数据提供者对象完全能够将数据从 Net DateTime
值来回转换为 MySql 需要根据列定义存储它的任何方式。
真正的问题可能在这里:
Dim timedifference As Integer = DateTime.Compare(nowtime, thishostlastpoll)
鉴于变量名称及其显示方式,您可能对 DateTime.Compare
的作用感到困惑。来自 MSDN :
Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.
给定 2 个定义为 TIMESTAMP(3)
的 MySql 列并读入 NET DateTime
变量:
Console.WriteLine("A is {0}", dtA)
Console.WriteLine("B is {0}", dtB)
Console.Write("Compare is {0}, therefore ", DateTime.Compare(dtA, dtB))
Select Case DateTime.Compare(dtA, dtB)
Case Is < 0 ' ie -1
Console.WriteLine("dtA is earlier")
Case Is > 0
Console.WriteLine("dtB is earlier")
Case 0
Console.WriteLine("dtA and dtB are exactly equal")
End Select
结果:
A is 1/18/2016 8:39:51 AM
B is 1/18/2016 8:40:11 AM
Compare is -1 therefore, dtA is earlier
DateTime.Compare
可能有点令人困惑的是,结果指示较早/较小 值,而大多数其他比较
方法指示较大。
关于mysql - 比较来自mysql的两个时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34853232/