【问题标题】:Difference between two dates in number of months and days SQL两个日期在月数和天数方面的差异 SQL
【发布时间】:2020-08-05 16:11:21
【问题描述】:

我试图显示两个日期之间的差异以计算月租金,我预计确切的月数和天数,因为合同是“每月”的,所以如果是 2 月、3 月或 4 月,每月金额是固定的。 所以让我们说: Strat_D = 2020 年 8 月 5 日 End_D = 2020 年 9 月 20 日 我正在使用此代码来获取天数:

DateDiff("d",[Start_D],[End_D])

输出为:45,但预期:1 个月和 15 天或 1.5

如果我使用:

DateDiff("m",[Start_D],[End_D])

输出为:1,但期望:1.5

提前致谢

【问题讨论】:

  • 这很棘手。如果开始日期是 2020 年 1 月 31 日,结束日期是 2020 年 2 月 18 日怎么办?
  • 是的,你不能轻易做到这一点,因为月份的天数是可变的,并且有不同的方法来处理它(例如,通过查看最后的天数来计算分数月,将所有月份固定为 365.25/12 = 30.44 天并据此计算)。我相信第一个在做金融工作时更常见,第二个更常见于统计数据以避免长期和短期的低谷/高峰。

标签: sql ms-access-2016


【解决方案1】:

由于月份的天数会有所不同,您必须按天数来尽可能接近,因为永远不会(一个月内或 7 月/8 月或 12 月/1 月内除外)会有一个确切的值:

' Returns the decimal count of months between Date1 and Date2.
'
' Rounds by default to two decimals, as more decimals has no meaning
' due to the varying count of days of a month.
' Optionally, don't round, by setting Round2 to False.
'
' 2017-01-24. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function TotalMonths( _
    ByVal Date1 As Date, _
    ByVal Date2 As Date, _
    Optional Round2 As Boolean = True) _
    As Double
    
    Dim Months      As Double
    Dim Part1       As Double
    Dim Part2       As Double
    Dim Fraction    As Double
    Dim Result      As Double
    
    Months = DateDiff("m", Date1, Date2)
    Part1 = (Day(Date1) - 1) / DaysInMonth(Date1)
    Part2 = (Day(Date2) - 1) / DaysInMonth(Date2)
    
    If Round2 = True Then
        ' Round to two decimals.
        Fraction = (-Part1 + Part2) * 100
        Result = Months + Int(Fraction + 0.5) / 100
    Else
        Result = Months - Part1 + Part2
    End If
    
    TotalMonths = Result
    
End Function


' Returns the count of days of the month of Date1.
'
' 2016-02-14. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DaysInMonth( _
    ByVal Date1 As Date) _
    As Integer

    Const MaxDateValue  As Date = #12/31/9999#
    Const MaxDayValue   As Integer = 31

    Dim Days    As Integer

    If DateDiff("m", Date1, MaxDateValue) = 0 Then
        Days = MaxDayValue
    Else
        Days = Day(DateSerial(Year(Date1), Month(Date1) + 1, 0))
    End If

    DaysInMonth = Days

End Function

结果:

? TotalMonths(#2020/08/05#, #2020/09/20#)
 1.5

? TotalMonths(#2020/11/15#, #2021/02/15#)
 3.03 

【讨论】:

    猜你喜欢
    • 2013-09-11
    • 2012-07-15
    • 2016-08-04
    • 2014-10-12
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多