Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 不使用DateDiff返回确切的日期差_Vb.net_Date - Fatal编程技术网

Vb.net 不使用DateDiff返回确切的日期差

Vb.net 不使用DateDiff返回确切的日期差,vb.net,date,Vb.net,Date,我需要以字符串的形式返回两个日期之间的精确差值 如果日期为2012年2月1日和2014年2月1日,则函数应返回“2年”。 如果日期为2012年2月1日和2014年3月1日,则函数应返回“25个月”。 如果差异不是以精确的年或月为单位,则应以天为单位返回差异 我不想使用Visual Basic名称空间中的DateDiff,因此代码可以移植到C#。' 公共函数GetDateDiff(d1作为DateTime,d2作为DateTime)作为字符串 如果d1.天=d2.天,则 Dim yearDiff为

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

如果日期为
2012年2月1日
2014年2月1日
,则函数应返回“2年”。
如果日期为2012年2月1日和2014年3月1日,则函数应返回“25个月”。
如果差异不是以精确的年或月为单位,则应以天为单位返回差异

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

'
公共函数GetDateDiff(d1作为DateTime,d2作为DateTime)作为字符串
如果d1.天=d2.天,则
Dim yearDiff为整数=d2.年-d1.年
如果d1.月=d2.月,则
“只有年份不同
返回年份差异和“年份”
其他的
“月与年不同
Dim monthDiff为整数=d2.月-d1.月
报税表(年差*12+月差)和“月”
如果结束
其他的
返回(d2-d1)。总天数和“天数”
如果结束
端函数

为什么不在C#code中导入
DateDiff
程序集?或者,您可以使用
DateTime.Subtract
'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