在我的VB应用程序中,我们可以基于各种预定义的日期范围(例如“本周”和“上个月”)运行报告。我想为“下个月”添加一个新范围。
似乎我们定义的现有日期范围的编码方式与到目前为止我发现的其他解决方案不同。我还尝试了一些变体,我认为这些变体是合乎逻辑的,并且可以证明是正确的。可悲的是,我还没有成功。
我们目前在VB中定义的范围的格式如下:
Case 3 'This Week
StartDate = Now.Date.AddDays(-Now.Date.DayOfWeek)
EndDate = Now.Date.AddDays(6 - Now.Date.DayOfWeek)
Case 4 'This Month
StartDate = Now.Date.AddDays(-(Now.Day - 1))
EndDate = New DateTime(Now.Year, Now.Month, Date.DaysInMonth(Now.Year, Now.Month))
答案 0 :(得分:8)
下个月很容易:
Dim nexMonth = Date.Today.AddMonths(1)
StartDate = New Date(nexMonth.Year, nexMonth.Month, 1)
EndDate = StartDate.AddMonths(1).AddDays(-1) ' or like you did in Case4 but with nexMonth
答案 1 :(得分:-1)
Rango,如果Today
是3月31日,那么您的逻辑可能会有问题,因为下个月4月只有30天。但是解决方法很简单:
Dim startOfThisMonth = New Date(Date.Today.Year, Date.Today.Month, 1)
Dim nextMonth = startOfThisMonth.AddMonths(1)
...等等...
换句话说,首先计算您当前所在月份的第一天,然后计算从当天当天(而不是今天)显示的日期。
(如果Microsoft已经预料到这一点,那么您提供的解决方案实际上在任何一天都是正确的,请原谅。)
答案 2 :(得分:-1)
一些共享方法FWIW
Public Class DateRanges
Public Class DateRange
Public StartDate As Date
Public EndDate As Date
End Class
Public Shared Function ThisWeek(d As Date) As DateRange
Dim rv As New DateRange
rv.StartDate = d.AddDays(-d.DayOfWeek)
rv.EndDate = rv.StartDate.AddDays(6)
Return rv
End Function
Public Shared Function NextWeek(d As Date) As DateRange
Dim rv As DateRange = ThisWeek(d)
rv.StartDate = rv.StartDate.AddDays(7)
rv.EndDate = rv.EndDate.AddDays(7)
Return rv
End Function
Public Shared Function PreviousWeek(d As Date) As DateRange
Dim rv As DateRange = ThisWeek(d)
rv.StartDate = rv.StartDate.AddDays(-7)
rv.EndDate = rv.EndDate.AddDays(-7)
Return rv
End Function
Public Shared Function ThisMonth(d As Date) As DateRange
Dim rv As New DateRange
rv.StartDate = d.AddDays(-d.Day + 1)
rv.EndDate = rv.StartDate.AddDays(Date.DaysInMonth(rv.StartDate.Year,
rv.StartDate.Month) - 1)
Return rv
End Function
Public Shared Function NextMonth(d As Date) As DateRange
Dim rv As DateRange = ThisMonth(d)
rv.StartDate = rv.EndDate.AddDays(1)
rv.EndDate = rv.StartDate.AddDays(Date.DaysInMonth(rv.StartDate.Year,
rv.StartDate.Month) - 1)
Return rv
End Function
Public Shared Function PreviousMonth(d As Date) As DateRange
Dim rv As DateRange = ThisMonth(d)
rv.EndDate = rv.StartDate.AddDays(-1)
rv.StartDate = rv.EndDate.AddDays(-Date.DaysInMonth(rv.EndDate.Year,
rv.EndDate.Month) + 1)
Return rv
End Function
End Class
使用方法
Dim r As DateRanges.DateRange
r = DateRanges.ThisWeek(Date.Now)
r = DateRanges.NextWeek(#1/30/2019#)
r = DateRanges.PreviousWeek(#1/30/2019#)
r = DateRanges.ThisMonth(#1/30/2019#)
r = DateRanges.NextMonth(r.StartDate)
r = DateRanges.PreviousMonth(r.StartDate)
r = DateRanges.NextMonth(Date.Now)