簡體   English   中英

如何將Vb.net中的DateTime舍入到最接近的5分鍾

[英]How to Round DateTime in Vb.net to the nearest 5mins

我正在編寫一些數據分析軟件,我想擴展原始數據的時基。 我的原始數據的時間步長約為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分鍾,而不是向上或向下舍入到NEAREST 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,以獲得“四舍五入到五分鍾”的功能:

' 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM