我有两个日期的时间格式是YYYY-MM-dd hh:mm:ss。
我有一个24H标准的时间范围。从5:30到21:00是白天,从21:00到5:30是晚上。
我必须检查这段时间中有多少时间(以秒为单位)是黑夜,有多少时间是白昼。
下面是一个例子。
我有两个日期创建一个周期:
date1 = 2016-08-08 12:31:35 (start)
date2 = 2016-08-09 00:29:11 (end)
从12:31:35到21:00是34105秒,从21:00:00到0:29:11是12555秒。
所以,在我的周期,我有34105在白天和12551在晚上。
当我有例如从2016-08-08 12:31:35到2016-08-10 12:31:35,而我有两天例假时,我该如何解决?
VBA将Date类型存储为浮点数,时间在小数点的右边,日期在左边。您可以通过只取小数部分来得到时间分量:
time = someDate - Int(someDate)
因此,您可以定义一些有用的常量来计算如何将时间部分划分为白天和黑夜:
Const ONE_SECOND = 1 / 24 / 60 / 60
Const DAY_START = ONE_SECOND * 60 * 60 * 5.5
Const DAY_END = ONE_SECOND * 60 * 60 * 21
Const MIDNIGHT = 1
Const SECONDS_IN_DAY = DAY_END - DAY_START
然后创建一个简单的辅助函数来将Double转换为总秒数:
Public Function TotalSeconds(inValue As Double)
TotalSeconds = Int(inValue) * 24 * 60 * 60 + _
Hour(inValue) * 60 * 60 + _
Minute(inValue) * 60 + _
Second(inValue)
End Function
然后,只需确定日期是否相同,并根据开始和结束是否在同一天对Double部分做一些简单的计算:
Private Sub Sample()
Dim starting As Date, ending As Date
starting = CDate("2016-08-08 12:31:35")
ending = CDate("2016-08-09 00:29:11")
Dim days As Long
'Calculate number of days between dates.
days = Int(ending) - Int(starting)
'Remove the date portions
starting = starting - Int(starting)
ending = ending - Int(ending)
Dim day As Double, night As Double
If days = 0 Then 'Same day?
day = SECONDS_IN_DAY
If starting < DAY_START Then
night = night + DAY_START - starting
Else
day = day - (starting - DAY_START)
End If
If ending > DAY_END Then
night = night + (ending - DAY_END)
Else
day = day - (DAY_END - ending)
End If
Else
'seconds from the first day.
If starting > DAY_END Then
night = MIDNIGHT - starting
Else
night = MIDNIGHT - DAY_END
If starting > DAY_START Then
day = DAY_END - starting
Else
day = SECONDS_IN_DAY
night = night + (DAY_START - starting)
End If
End If
'seconds from the last day.
If ending > DAY_END Then
night = night + (ending - SECONDS_IN_DAY)
day = day + SECONDS_IN_DAY
Else
If ending < DAY_START Then
night = night + ending
Else
night = night + DAY_START
day = day + (ending - DAY_START)
End If
End If
'seconds from full days in between
If days > 1 Then
night = night + ((days - 1) * (1 - SECONDS_IN_DAY))
day = day + ((days - 1) * SECONDS_IN_DAY)
End If
End If
Debug.Print "Day: " & TotalSeconds(day), "Night: " & TotalSeconds(night)
End Sub
我有类似的问题,我使用了不同的解决方案。我必须在一天中的特定时间启用3个表单,其中一个表单是从晚上11点到早上7点。
我的解决方案(示例):
If Not (DateAdd("h", 8, TimeValue(Now)) > DateAdd("h", 8, Sheets(1).Range("B25").Value) And DateAdd("h", 8, TimeValue(Now)) < DateAdd("h", 8, Sheets(1).Range("B25").Value)) Then
基本上,我是根据单元格值加上8小时来进行所有计算的,所以我实际上可以避免在午夜工作。
DateAdd("h", 8, TimeValue(Now))
这应该有助于在某些情况下保持代码非常简单和简短。帮助参考:https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dateadd-function