日期之间的季度数 [英] Count of quarter between dates

查看:136
本文介绍了日期之间的季度数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在给定的时间跨度计算总宿舍(一年)的数量。

I want to calculate the count of total quarters (of a year) in the given time span.

例如:

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.

我一直没能得到正确的结果。

I have not been able to get the correct result.

推荐答案

您的例子是错误的:只有7 间宿舍4月 - 2009年 27 - 10月-2010

Your example is wrong: there are only 7 quarters between 4-Jan-2009 and 27-oct -2010

您可以在 Microsoft.VisualBasic.dll中引用只需添加到您的项目,并使用则DateDiff

You could simply add a reference to the Microsoft.VisualBasic.dll to your project and use 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);
}

或者你可以写自己的实现:

or you could write your own implementation:

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

这篇关于日期之间的季度数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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