計算起迄日之差異年月日(含閏年)

  • 9066
  • 0

計算起迄日之差異年月日(含閏年)

Dotblogs 的標籤: ,

今天中午吃飯時收到的需求,要計算起迄日區間之差異的年、月、日,且起日即為有效日,所以2010/1/1 ~ 2010/1/1算 1 天。需求要求要包含閏年,透過dotNet的日期函數,倒是不用特別處理 ^^

查了網路上有很多種做法,但是大多是除以 365 算年,除以 30 算月,就無法符合需求了,所以乾脆自己邊吃飯邊寫一隻~

    ''' Desc: 計算日期區間的差異年、月、日,含閏年計算
    ''' Author: Leo Shih
    ''' Date: 2010/09/29
    ''' </summary>
    Private Function CalDateDiffRange(ByVal StartDate As Date, ByVal EndDate As Date) As NameValueCollection
        Dim nvcRange As New NameValueCollection
        Dim iYearDiff As Integer = 0
        Dim iMonthdiff As Integer = 0
        Dim iDayOfMonthDiff As Integer = 0
        Dim lgCostDay As Long = 0
        Dim lgUsedDay As Long = 0
        Dim lgTempSumDay As Long = 0
        '取得起迄日期區間的實際日數,因為起日就算有效日,所以要 +1
        Dim lgActRangeDay As Long = DateDiff(DateInterval.DayOfYear, StartDate, EndDate) + 1

        '計算差距年
        While (True)
            '起日累加年,取得差距天數
            lgCostDay = DateDiff(DateInterval.DayOfYear, StartDate, DateAdd(DateInterval.Year, iYearDiff + 1, StartDate))
            '累加後的差距天數<=實際差天數,就繼續累加年份
            If lgCostDay <= lgActRangeDay Then
                '表示超過一年
                iYearDiff += 1
                lgUsedDay = lgCostDay
            Else
                Exit While
            End If
        End While
        Dim dteCurrent As Date = DateAdd(DateInterval.Year, iYearDiff, StartDate)
        '計算差距月
        While (True)
            '累加一個月,取差距天數
            lgCostDay = DateDiff(DateInterval.Day, dteCurrent, DateAdd(DateInterval.Month, iMonthdiff + 1, dteCurrent))
            '若差距天數+差距年數之天數<=實際差天數,就繼續累加月份
            If (lgUsedDay + lgCostDay) <= lgActRangeDay Then
                iMonthdiff += 1
                lgTempSumDay = lgCostDay
            Else
                Exit While
            End If
        End While
        lgUsedDay += lgTempSumDay
        '計算差距日
        iDayOfMonthDiff = CType((lgActRangeDay - lgUsedDay), Integer)

        Console.WriteLine("起:" & StartDate.ToShortDateString & ", 迄:" & EndDate.ToShortDateString)
        Console.WriteLine(iYearDiff.ToString & "年" & iMonthdiff.ToString & "月" & iDayOfMonthDiff.ToString & "天")
        nvcRange.Set("YearDiff", iYearDiff.ToString)
        nvcRange.Set("MonthDiff", iMonthdiff.ToString)
        nvcRange.Set("DayOfMonthDiff", iDayOfMonthDiff.ToString)
        Return nvcRange
    End Function

--------
沒什麼特別的~
不過是一些筆記而已