gpt4 book ai didi

c# - 日期之间的季度计数

转载 作者:行者123 更新时间:2023-11-30 19:47:34 26 4
gpt4 key购买 nike

我想计算给定时间跨度内(一年)的总季度数。

例如:

start date = 1-june -2009
end date = 18-july-2011

count should be = 10.

one more
start date = 4-Jan-2009
end date = 27-oct -2010
count =8.

我没能得到正确的结果。

最佳答案

您的示例是错误的:4-Jan-2009 之间只有 7 个季度和 27-oct -2010

您可以简单地添加对 Microsoft.VisualBasic.dll 的引用到您的项目并使用 DateDiff :

VB:

Public Shared Function getQuartersBetween(ByVal d1 As Date, ByVal d2 As Date) As Int32
Return DateDiff(DateInterval.Quarter, d1, d2)
End Function

C#:

public static int getQuartersBetween(System.DateTime d1, System.DateTime d2)
{
return Microsoft.VisualBasic.DateAndTime.DateDiff(DateInterval.Quarter, d1, d2);
}

或者您可以编写自己的实现:

public class Quarter
{

public static long GetQuarters(DateTime dt1, DateTime dt2)
{
double d1Quarter = GetQuarter(dt1.Month);
double d2Quarter = GetQuarter(dt2.Month);
double d1 = d2Quarter - d1Quarter;
double d2 = (4 * (dt2.Year - dt1.Year));
return Round(d1 + d2);
}

private static int GetQuarter(int nMonth)
{
if (nMonth <= 3)
return 1;
if (nMonth <= 6)
return 2;
if (nMonth <= 9)
return 3;
return 4;
}

private static long Round(double dVal)
{
if (dVal >= 0)
return (long)Math.Floor(dVal);
return (long)Math.Ceiling(dVal);
}
}

或在 VB.NET 中:

Public Class Quarter

Public Shared Function GetQuarters(ByVal dt1 As DateTime, ByVal dt2 As DateTime) As Long
Dim d1Quarter As Double = GetQuarter(dt1.Month)
Dim d2Quarter As Double = GetQuarter(dt2.Month)
Dim d1 As Double = d2Quarter - d1Quarter
Dim d2 As Double = (4 * (dt2.Year - dt1.Year))
Return Round(d1 + d2)
End Function

Private Shared Function GetQuarter(ByVal nMonth As Integer) As Integer
If nMonth <= 3 Then
Return 1
End If
If nMonth <= 6 Then
Return 2
End If
If nMonth <= 9 Then
Return 3
End If
Return 4
End Function

Private Shared Function Round(ByVal dVal As Double) As Long
If dVal >= 0 Then
Return CLng(Math.Floor(dVal))
End If
Return CLng(Math.Ceiling(dVal))
End Function

End Class

关于c# - 日期之间的季度计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6592580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com