我需要在 vb.net 中计算当前季度和上一季度的 StartDate 和 EndDate。
3 回答
我知道你指定VB.Net
了,但我更愿意在C#
. 如果需要,我相信有人可以翻译。
public static DateTime QuarterEnd() {
DateTime now = DateTime.Now;
int year = now.Year;
DateTime[] endOfQuarters = new DateTime[] {
new DateTime(year, 3, 31),
new DateTime(year, 6, 30),
new DateTime(year, 9, 30),
new DateTime(year, 12, 31)
};
return endOfQuarters.Where(d => d.Subtract(now).Days >= 0).First();
}
我更喜欢这个解决方案而不是其他涉及模算术和丑陋条件的解决方案,因为它很容易修改以处理非标准季度定义。方法的定义QuarterStart
类似处理,留给亲爱的读者作为练习。或者,您可以修改此方法以返回struct
包含所需开始和结束日期的 a。
编辑,添加上述 C#-code /Stefan的 VB.Net 版本:
Public Function QuarterEnd() As Date
Dim endOfQuarters As Date() = New Date() { _
New Date(Now.Year, 3, 31), _
New Date(Now.Year, 6, 30), _
New Date(Now.Year, 9, 30), _
New Date(Now.Year, 12, 31)}
Return endOfQuarters.Where(Function(d) d.Subtract(Now).Days >= 0).First()
End Function
请原谅我缺乏特定于 VB.net 的答案,但给出了一种通用的日期对象,它具有一些伪语言中的各种功能(具有从零开始的日期和月份索引)......
//round the current month number down to a multiple of 3
ThisQuarterStart = DateFromYearMonthDay(Today.Year,Today.Month-(Today.Month%3),0);
//round the current month number up to a multiple of 3, then subtract 1 day
ThisQuarterEnd = DateFromYearMonthDay((Today.Month<9)?(Today.Year):(Today.Year+1),(Today.Month-(Today.Month%3)+3)%12,0) - 1;
//same as above, but minus 3 months
LastQuarterStart = DateFromYearMonthDay((Today.Month<3)?(Today.Year-1):(Today.Year),(Today.Month-(Today.Month%3)+9)%12,0)
LastQuarterEnd = ThisQuarterStart - 1;
编辑将上述伪代码转换为工作VB.Net:/Stefan
Dim ThisQuarterStart As Date = New Date(Today.Year, Today.Month - (Today.Month Mod 3) + 1, 1)
Dim ThisQuarterEnd As Date = New Date(CInt(IIf(Today.Month < 9, Today.Year, Today.Year + 1)), (Today.Month - (Today.Month Mod 3) + 3 Mod 12) + 1, 1).AddDays(-1)
Dim LastQuarterStart As Date = New Date(CInt(IIf(Today.Month < 3, Today.Year - 1, Today.Year)), (Today.Month - (Today.Month Mod 3) + 9 Mod 12) + 1, 1)
Dim LastQuarterEnd As Date = ThisQuarterStart.AddDays(-1)
vb.net 转换需要更改。将其更改为 vb 6,它应该是;
ThisQuarterStart = DateSerial(today.Year, today.Month - (IIf(today.Month Mod 3 = 0, 3, today.Month Mod 3)) + 1, 1)
ThisQuarterEnd = DateSerial(CInt(IIf(today.Month < 9, today.Year, today.Year + 1)), ((today.Month - (IIf(today.Month Mod 3 = 0, 3, today.Month Mod 3) )) + 3) 模型 12) + 1, 1) - 1