【问题标题】:Returning the exact date difference without using DateDiff在不使用 DateDiff 的情况下返回确切的日期差异
【发布时间】:2012-01-19 14:50:28
【问题描述】:

我需要以字符串的形式返回两个日期之间的确切差异。

如果日期是01-FEB-201201-FEB-2014,则函数应返回“2 年”。
如果日期是01-FEB-201201-MAR-2014,则函数应返回“25 个月”。
如果差异不是精确的年或月,它应该以天为单位返回差异。

我不想使用 Visual Basic 命名空间中的 DateDiff,因此代码可以移植到 C#。

【问题讨论】:

  • 为什么不在 C# 代码中导入 DateDiff 程序集?或者,您可以使用DateTime.Subtract

标签: vb.net date


【解决方案1】:
'Assuming d1 < d2    
Public Function GetDateDiff(d1 as DateTime, d2 As DateTime) As String

    If d1.Day = d2.Day Then
        Dim yearDiff As Integer = d2.Year - d1.Year
        If d1.Month = d2.Month Then
            'Only year differs
            Return yearDiff & " years"
        Else
            'Month and year differs
            Dim monthDiff As Integer = d2.Month - d1.Month
            Return (yearDiff * 12 + monthDiff) & " months"
        End If
    Else
        Return (d2-d1).TotalDays & " days"
    End If
End Function

【讨论】:

    猜你喜欢
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多