我的代码在下面工作正常,显示为年,月和日。所以如下所示,我总结只显示我做了一些转换。我在我的代码中遇到一些小问题。我的年份显示330而不是365.如果我输入1年它应该显示365,1个月应该是30 ..但是如果34天它应该显示为34,而不是它显示为60days.anyone可以弄明白怎么来我在下面的代码中得到了这个错误。这是我在ssrs 2008中的报告属性中的代码
Public Function ILength(length As Integer ) As String
dim year As Integer=0
dim month As Integer=0
dim day As Integer=0
dim sum as integer
if(length =0)
Return String.Empty
end if
if length >= 366 then
year=cstr(Math.Floor (length/ 365.25))
length =(length Mod 365.25)
length =(year * 365)
year =cstr(length)
end if
if length>31 Andalso length<366 then
month=cstr (Math.Floor(length/30.4375))
length=(length Mod 30.4375)
length=(month * 30)
month=cstr(length)
end if
if length<31 Then
day =cstr(length)
end if
if length = 0 then
Return String.Empty
end if
sum= ((year)+(month)+(day))
return(sum)
End Function
由于
答案 0 :(得分:0)
正如B Pete所说,你正在重新发明轮子。 Visual Basic运行时库函数全部可用,并已经过数千名开发人员的测试和使用:
http://msdn.microsoft.com/en-us/library/c157t28f.aspx
E.g。 DateDiff的
答案 1 :(得分:0)
您的逻辑存在一些问题。
假设你有充分的理由做这一切(请分享!)并且不能使用像=datediff(d,fields!FirstDate.Value,fields!SecondDate.value)
这样简单的东西
然后我可以告诉你这个功能出错的地方。
在这部分:
if length >= 366 then
year=cstr(Math.Floor (length/ 365.25))
length =(length Mod 365.25)
length =(year * 365)
year =cstr(length)
输入值为367.第二行将为您提供年份= 1。第三行将给你length = 0。是的,零。你已经将所有内容都声明为整数,并且整数会明确地截断任何尾数(小数点后面的位)。您希望将这些声明为浮点或更好,一个精确的数字。第四行用Year(1)* 365 = 365覆盖你的长度值。然后第五行将365转换为字符串并将其分配给year,除了year是一个整数,因此它被隐式地强制转换为整数。如果您的变量被声明为正确的类型,您只需要这3行,但366天的事情再次非常农业。它很难处理边缘情况。
if length >= 366 then
year=cstr(Math.Floor (length/ 365.25))
length =(length Mod 365.25)
下一部分:
if length>31 Andalso length<366 then
这也是必要的。您已经在代码的第一部分确保长度现在小于365(如果变量是正确的数据类型,那么长度将小于365.25)
这就够了:
if length>31 then
你在下一部分做了同样的事情,前两行就足够了,再次假设你的数据类型是固定的。
month=cstr (Math.Floor(length/30.4375))
length=(length Mod 30.4375)
length=(month * 30)
month=cstr(length)
在接下来的部分中,它起作用(除了Cstr之外),但是不舒服。在测试长度&lt;之前,你应该检查长度= 0。 31.
if length<31 Then
day =cstr(length)
end if
if length = 0 then
Return String.Empty
end if
你在评论中说了两个相互矛盾的陈述。首先,您有输入,如年/月日和秒,您有开始和结束日期参数。如果第二个是真的并且你有开始/结束日期,那么扔掉这个代码并使用datediff。内置函数已经考虑了闰年和几个月的实际长度,无需使用粗均值。
看起来你已经使用了自定义代码,这是一个解决非存在问题的复杂解决方案。