简体   繁体   中英

Datediff in MsAccess

I am stuck in one place. I am using DateDiff in Ms Access it is giving me proper output, like

StartDate is 10-Sep-2016
EndDate is 15-Oct-2016

Total Days which I will get is 35
& months will i get is 1 Month

DateDiff('d',StartDate,EndDate)

**But I want output as 2 months if it is exeeded the 30 days. if it is 61 days then 3 months & so on.

**IIFFF days diffrence is 
   29 Days then output should be 1 months
   30 Days then output should be 1 months
   32 Days then output should be 2 months
   60 Days then output should be 2 months
   62 Days then output should be 3 months**

Will that be possible in the DateDiff in MsAccess or is there any other function available so that i can achieve the same output.**

You can do this using conditional logic. Perhaps something like this:

select iif(DateDiff('d', StartDate, EndDate) > 30,
           DateDiff('d',StartDate,EndDate) & " days",
           "2 months"
          )

Your logic that anything exceeding 30 days is "2 months" seems strange. Normally, I think the logic would look like this:

select iif(DateDiff('d', StartDate, EndDate) > 30,
           DateDiff('d', StartDate, EndDate) & " days",
           DateDiff('m', StartDate, EndDate) & " months"
          )

It seems like your minimum count of months for a positive count of days is 1, thus:

MonthCount = Sgn(DateDiff("d",StartDate,EndDate)) + DateDiff("m",StartDate,EndDate)

Edit

For a 30-day cut that will produce your example output, use this simple formula in your query:

MonthCount: (DateDiff("d",[StartDate],[EndDate])-1)\30+1

will this logic suffice to modify your SQL function?

Public Function FN_GET_MONTH(iDays As Long, Optional iDaysInMonth As Long = 30)

    If (iDays / iDaysInMonth) > iDays \ iDaysInMonth Then
        FN_GET_MONTH = (iDays \ iDaysInMonth) + 1
    Else
        FN_GET_MONTH = (iDays \ iDaysInMonth)
    End If

End Function

?FN_GET_MONTH(29) = 1
?FN_GET_MONTH(31) = 2
?FN_GET_MONTH(60) = 2
?FN_GET_MONTH(80) = 3
?FN_GET_MONTH(91) = 4

you can have this public function and use it in your SQL code like

FN_GET_MONTH(DateDiff("d", StartDate, EndDate))

This query seems to give the results you seek:

SELECT 
    StartDate,
    EndDate
    numDays,
    ((numDays - 1) \ 30) + 1 AS numMonths
FROM
    (
        SELECT
            StartDate,
            EndDate,
            DateDiff("d", StartDate, EndDate) AS numDays
        FROM YourTable
    )

It gives me

numDays  numMonths
-------  ---------
...
     29          1
     30          1
     31          2
     32          2
...
     59          2
     60          2
     61          3
     62          3
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM