在两个日期之间显示的计数周数错误. [英] Number of count weeks display wrong in between two dates.

查看:91
本文介绍了在两个日期之间显示的计数周数错误.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有两个日期,例如开始日期"和结束日期".

当我计算两个日期的星期数时,它显示为空.

始发日期:2011/12/1
迄今为止:2011年12月22日

星期的差异计数是:3(但是,它显示错误).

这是什么问题..

看看我的代码...
-----------

Hi,

I have the two date''s such as From Date and To Date.

When i take a count of week for the Two Date''s it showing empty.

From Date : 12/1/2011
To Date : 12/22/2011

Difference Count of week is : 3 ( But, it''s showing wrong).

What is the problem here..

see my code...
-----------

If txtStartdate.Text <> "" And txtEndDate.Text <> "" Then
           Dim WeeksDiff As Integer
           Dim monthsApart As Integer = 12 * (StDate.Year - EdDate.Year) + StDate.Month - EdDate.Month
           WeeksDiff = Math.Abs(monthsApart * 4)
           txtDuration.Text = WeeksDiff
       End If

推荐答案

其他解决方案应为您提供所需的东西,以得到期望的答案.如果您为示例手动执行计算,则代码问题(您所提出的问题)很明显.由于您的两个日期(2011年12月1日和2011年12月22日)的StDate.Year = EndDate.Year和StDate.Month = EndDate.Month,因此,您的monthsApart = 12 x 0 + 0 =0.那么WeeksDiff = 0 * 4 =0.我认为您的评论是答案显示为空,实际上意味着答案为0.

如果测试用例未返回预期结果,请检查编码和算法.
The other solutions should give you what you need to get the answer you expect. The problem with your code (a question you asked) is obvious if you manually perform the calculations for your example. Since StDate.Year = EndDate.Year and StDate.Month = EndDate.Month for your two dates, (12/1/2011 and 12/22/2011), you have monthsApart= 12 x 0 + 0 = 0. Then WeeksDiff = 0 * 4 = 0. I assume your comment that the answer shows empty actually means the answer is 0.

If test cases don''t return the expected result check both the coding and the algorithm.


主要问题是一个月中没有4周:有28/7、29/7、30/7或31/7.只有4个.

试试这个:
The major problem is that there aren''t 4 weeks in a month: there are 28/7, 29/7, 30/7, or 31/7. Only one of which is 4.

Try this:
Public Shared Function NumberOfWeeks(dateFrom As DateTime, dateTo As DateTime) As Integer
	Dim diff As TimeSpan = dateTo.Subtract(dateFrom)

	If diff.Days <= 7 Then
		If dateFrom.DayOfWeek > dateTo.DayOfWeek Then
			Return 2
		End If
		Return 1
	End If

	Dim Days As Integer = diff.Days - 7 + CInt(dateFrom.DayOfWeek)
	Dim WeekCount As Integer = 1
	Dim DayCount As Integer = 0
	WeekCount = 1
	While DayCount < Days
		DayCount += 7
		WeekCount += 1
	End While

	Return WeekCount
End Function


选中此链接 [

这篇关于在两个日期之间显示的计数周数错误.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆