MS Access select between two dates?

冷暖自知 提交于 2021-02-05 09:42:30

问题


I have searched, but all results didn't help me to understand.

I need to select names of people who are 18-23 years old. So my try was:

WHERE ((People.Birth) Between (Now()-Year(18)) And (Now()-Year(23)))

What I'm doing wrong? Solution as #some_date# is a bad idea!


回答1:


For a true solution, you need to use DateAdd and a function like this:

Public Function AgeSimple( _
  ByVal datDateOfBirth As Date) _
  As Integer

' Returns the difference in full years from datDateOfBirth to current date.
'
' Calculates correctly for:
'   leap years
'   dates of 29. February
'   date/time values with embedded time values
'
' DateAdd() is used for check for month end of February as it correctly
' returns Feb. 28. when adding a count of years to dates of Feb. 29.
' when the resulting year is a common year.
' After an idea of Markus G. Fischer.
'
' 2007-06-26. Cactus Data ApS, CPH.

  Dim datToday  As Date
  Dim intAge    As Integer
  Dim intYears  As Integer

  datToday = Date
  ' Find difference in calendar years.
  intYears = DateDiff("yyyy", datDateOfBirth, datToday)
  If intYears > 0 Then
    ' Decrease by 1 if current date is earlier than birthday of current year
    ' using DateDiff to ignore a time portion of datDateOfBirth.
    intAge = intYears - Abs(DateDiff("d", datToday, DateAdd("yyyy", intYears, datDateOfBirth)) > 0)
  End If

  AgeSimple = intAge

End Function

Then your query will have this where clause:

WHERE AgeSimple(People.Birth) Between 18 And 23



回答2:


Finally solved it by simple

WHERE ((People.Birth) Between (Now()- 365*18) And (Now()-365*23))

If you have better solution- welcome



来源:https://stackoverflow.com/questions/35331016/ms-access-select-between-two-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!