Access中的日期差异:dd:hh:mm

时间:2016-11-15 12:28:18

标签: sql ms-access-2010 ms-access-2013

我想计算字段中日期与今天dd:hh:mm fromat之间的日期差异。我试过以下

Format(DateDiff("s",FieldA,Date())/86400,"dd:hh:nn")

但上面的代码并没有给我正确的区别。例如,FieldA中的第一个值是04.11.2016 11:52:56。所以差异必须在11天左右。但是我得到了09:12:07的结果。我什么时候出错?

1 个答案:

答案 0 :(得分:0)

您可以使用下面的功能。然后:

TimePassed: FormatYearDayHourMinuteSecondDiff(#2016/11/04 11:52:56#, Date())

'TimePassed -> 0 11 12:07:04

它使用外部函数Years,但您可以轻松地将其修改为不显示年份。

Public Function FormatYearDayHourMinuteSecondDiff( _
  ByVal datTimeStart As Date, _
  ByVal datTimeEnd As Date, _
  Optional ByVal strSeparatorDate As String = " ", _
  Optional ByVal strSeparatorTime As String = ":") _
  As String

' Returns count of years, days, hours, minutes and seconds of difference
' between datTimeStart and datTimeEnd converted to
' years, days, hours and minutes and seconds as a formatted string
' with an optional choice of date and/or time separator.
'
' Should return correct output for a negative time span but
' this is not fully tested.
'
' Example:
'   datTimeStart: #2006-05-24 10:03:02#
'   datTimeEnd  : #2009-04-17 20:01:18#
'   returns     : 2 328 09:58:16
'
' 2007-11-06. Cactus Data ApS, CPH.

  Const cintSecondsHour As Integer = 60& * 60&

  Dim intYears      As Integer
  Dim intDays       As Integer
  Dim intSeconds    As Integer
  Dim intHours      As Integer
  Dim datTime       As Date
  Dim strDatePart   As String
  Dim strTimePart   As String
  Dim strYDHMS      As String

  intYears = Years(datTimeStart, datTimeEnd)
  datTimeStart = DateAdd("yyyy", intYears, datTimeStart)
  intDays = DateDiff("h", datTimeStart, datTimeEnd) \ 24
  datTimeStart = DateAdd("d", intDays, datTimeStart)
  intHours = DateDiff("h", datTimeStart, datTimeEnd)
  datTimeStart = DateAdd("h", intHours, datTimeStart)
  intSeconds = DateDiff("s", datTimeStart, datTimeEnd)

  ' Format year and day part.
  strDatePart = CStr(intYears) & strSeparatorDate & CStr(intDays)
  datTime = TimeSerial(intHours, 0, intSeconds Mod cintSecondsHour)
  ' Format hour, minute and second part.
  strTimePart = Format(datTime, "hh\" & strSeparatorTime & "nn\" & strSeparatorTime & "ss")
  strYDHMS = strDatePart & " " & IIf(datTime < 0, "-", "") & strTimePart

  FormatYearDayHourMinuteSecondDiff = strYDHMS

End Function