vb.net 如何将 DateTime 转换为 Integer 并检查差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17433881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:07:22  来源:igfitidea点击:

How to convert DateTime to Integer and check the difference?

vb.net

提问by Kre?imir ?ulina

I'm trying to compare the difference between two times in the day. I'm getting time in UTC format. Do I have to convert DateTime to integer in order to get the difference and if yes how?

我正在尝试比较一天中两次之间的差异。我正在获取 UTC 格式的时间。我是否必须将 DateTime 转换为整数才能获得差异,如果是,如何转换?

This is my code

这是我的代码

Dim ct As DateTime = DateTime.UtcNow
        Dim int_ct As Integer = Convert.ToInt32(ct)
        MsgBox(ct + " | " + int_ct)
        If (System.IO.File.Exists(System.IO.Path.GetTempPath.ToString + "\tempfile.data")) Then
            Dim time As DateTime = System.IO.File.ReadAllText(System.IO.Path.GetTempPath.ToString + "\tempfile.data")
            Dim int_time As Integer = Convert.ToInt32(time)
            If ((int_ct - unlockedtime) < int_time) Then 'unlockedtime is Int variable
                Return False
            Else
                Return True
            End If
        End If

回答by Dai

You don't need to do any timezone conversion, just make sure that both date/time values are in the same timezone when you capture them (though I suppose it might be wise use to UtcNowin case the system timezone changes in-between your two measurements.

您不需要进行任何时区转换,只需确保捕获它们时两个日期/时间值都在同一时区中(尽管我认为UtcNow如果系统时区在您的两者之间发生变化,这可能是明智的使用测量。

You don't need to convert values to Int32to get the difference, just use the DateTime.Subtractmethod:

您不需要将值转换为Int32以获得差异,只需使用该DateTime.Subtract方法:

Dim old As DateTime = GetOldDateTime()
Dim now As DateTime = DateTime.UtcNow
Dim diff As TimeSpan = now.Subtract( old )

If diff.TotalSeconds > someSecondsValue Then
    DoSomething()
End If

回答by TrustedInSci

Have you tried Datetime.Compare(dt1,dt2)? Depending on how much detail you need this might work for you.

你试过 Datetime.Compare(dt1,dt2) 吗?根据您需要多少细节,这可能适合您。

Here is more information on the function: http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

以下是有关该功能的更多信息:http: //msdn.microsoft.com/en-us/library/system.datetime.compare.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

回答by OCDan

As Dai said you may want to compare difference, but if you just want the date difference you can use the following:

正如 Dai 所说,您可能想比较差异,但如果您只想要日期差异,则可以使用以下内容:

DateDiff(DateInterval.Minute, Date1, date2)

This returns the difference as an integer, you can set whatever date interval you require as the firt parameter.

这将差异作为整数返回,您可以将所需的任何日期间隔设置为 firt 参数。