如何将Vb.net中的DateTime四舍五入到最接近的5分钟



我正在写一些数据分析软件,我想升级我的原始数据的时基。我的原始数据的时间步长约为2分钟。我想将数据扩展到几个数据库表中,时间步长为5分钟、每小时、每天和每月。我计划从原始数据中运行每一个,以保持我的准确性。

我目前面临的问题是取一个初始值,然后找到我想要的最接近的"循环"时间点,作为我的起点。例如,我将以点13/03/12 00:01:36作为起点,我希望代码找到13/03/12 00:00:00作为最近的时间点,以便从那里开始计算。对于每一个时间点,我都想在每一边走一半的时间。因此,12/03/12 23:57:30到13/03/12 00:02:29将变为13/03/12 00:00:00。

使用SQL查询从Access获取数据,日期和值存储在两个并排的数组中。以下是到目前为止我的代码。它将把数值四舍五入到下一个5分钟,而不是向上或向下到最近的5分钟。

Private Sub RateStateScale(ByVal Parameter As Integer, ByVal Timebase As String)
Dim NewDate(0)
Dim NewData(0)
Dim RecordCounter
Dim MinValue As Date = ScaleDate(0)
Dim startpoint As String
For RecordCounter = 0 To ScaleDate.GetLength(0)
If MinValue > ScaleDate(RecordCounter) Then
MinValue = ScaleDate(RecordCounter)
End If
Next
Do Until MinValue.Minute Mod 5 = 0
MinValue = MinValue.AddMinutes(1)
Loop

End Sub

感谢您的帮助

让我们尝试一些VB,用于"四舍五入到最近的5分钟"函数:

' just some date, should be a parameter to your function
Dim mydatetime = new DateTime(2012,3,12,23,57,30)
' split into date + time parts
Dim datepart = mydatetime.Date
Dim timepart = mydatetime.TimeOfDay
' round time to the nearest 5 minutes
timepart = TimeSpan.FromMinutes(Math.Floor((timepart.TotalMinutes+2.5)/5.0) * 5.0)
' combine the parts
Dim newtime = datepart.Add(timepart)
' a function would return this value

一种可能性如下:

var date = new DateTime(2012,03,12,23,57,30);
var fullFiveMinutes = date.Minute / 5;
// result will be our date rounded down to the previous full five minutes
var result = new DateTime(date.Year, date.Month, date.Day
date.Hour, fullFiveMinutes * 5, 0);
// if we add exactly 2.5 minutes to our date variable and the result represents
// another full five minutes we need to round up.
if(date.AddSeconds(2.5 * 60).Minute / 5 != fullFiveMinutes)
result = result.AddMinutes(5);

这是C#代码,我相信你能翻译出来

你能帮忙吗?(非常基本,但它应该给出一个想法)

Dim tValue As Date = ScaleDate(0) 
'find the next highest 5 minute mark
For RecordCounter = 0 To ScaleDate.GetLength(0)              
If tValue > ScaleDate(RecordCounter) Then                  
tValue = ScaleDate(RecordCounter)              
End If          
Next  
Do Until tValue.Minute Mod 5 = 0         
tValue = tValue.AddMinutes(1)     
Loop
'compare the original value to the next highest.  If more than 2.5 minutes, then subtract 5 minutes
If DateDiff(DateInterval.Second, tValue, MinValue) > 150 Then
MinValue = tValue.AddMinutes(-5)
Else
MinValue = tValue
End If

我知道这已经有十年的历史了,但我就是这么做的。将时间除以5,这就得到了5分钟压缩的当前单位。该结果的整数可用于";向下取整";对于之前的5分钟压缩,现在添加5分钟以获得数据所属的压缩时间。

Dim ndate As DateTime = Now
Dim dt As DateTime = New DateTime(ndate.Year, ndate.Month, ndate.Day, ndate.Hour, Fix(ndate.Minute / 5) * 5, 0).AddMinutes(5)

最新更新