Format A TimeSpan With Years

后端 未结 6 1215
深忆病人
深忆病人 2020-11-27 06:45

I have a class with 2 date properties: FirstDay and LastDay. LastDay is nullable. I would like to generate a string in the format of

6条回答
  •  温柔的废话
    2020-11-27 07:31

    Public Function TimeYMDBetween(StartDate As DateTime, EndDate As DateTime) As String
        Dim Years As Integer = EndDate.Year - StartDate.Year
        Dim Months As Integer = EndDate.Month - StartDate.Month
        Dim Days As Integer = EndDate.Day - StartDate.Day
        Dim DaysLastMonth As Integer
    
        'figure out how many days were in last month
        If EndDate.Month = 1 Then
            DaysLastMonth = DateTime.DaysInMonth(EndDate.Year - 1, 12)
        Else
            DaysLastMonth = DateTime.DaysInMonth(EndDate.Year, EndDate.Month - 1)
        End If
    
        'adjust for negative days
        If Days < 0 Then
            Months = Months - 1
            Days = Days + DaysLastMonth 'borrowing from last month
        End If
    
        'adjust for negative Months
        If Months < 0 Then 'startdate hasn't happend this year yet
            Years = Years - 1
            Months = Months + 12
        End If
    
        Return Years.ToString() + " Years, " + Months.ToString() + " Months and " + Days.ToString() + " Days"
    
    End Function
    

提交回复
热议问题