在C#中计算当前月份的上一季度

时间:2015-03-03 17:41:01

标签: c# datetime calendar

'我确定有更简洁的方法来实现这一结果吗?但是我创建了以下方法来计算当前月份的上一季度或传入的DateTime。

void Main()
{
    var q = Helpers.PreviousQuarter();
    q.Dump();
}

public class Helpers
{
    public static int PreviousQuarter(DateTime? date = null)
    {
        var quarters = new Dictionary<int, int[]>();
        quarters.Add(1, new[] { 1, 2, 3 });
        quarters.Add(2, new[] { 4, 5, 6 });
        quarters.Add(3, new[] { 7, 8, 9 });
        quarters.Add(4, new[] { 10, 11, 12 });

        foreach (var q in quarters)
        {
            if (q.Value.Any(m=> m == (date.HasValue ? date.Value.Month : DateTime.Now.AddMonths(-3).Month)))
            return q.Key;
        }

        throw new ArgumentException("Could not calulate quarter.");
    }
}

3 个答案:

答案 0 :(得分:2)

private int PreviousQuarter(DateTime date)
{
        return (int)Math.Ceiling((double)date.AddMonths(-3).Month / (double)3);
}

答案 1 :(得分:0)

这应该可以解决问题

public static int PreviousQuarter(DateTime? date = null)
{
 int month;
   if (date.HasValue){
     month =  date.Value.Month;
   } else { 
     month = DateTime.Now.AddMonths(-3).Month)
   }
 float quarter =   month / 4;
 return (int)Math.Ceiling(quarter +0.1);
}

答案 2 :(得分:0)

您当前的代码返回当前季度的日期,您可以修改您的方法,如:

public static int CurrentQuarter(DateTime? date = null)
{
    return (((date ?? DateTime.Now.AddMonths(-3)).Month - 1) / 3) + 1;
}

如果您想计算之前的季度,那么您可以使用单个数组而不是字典,如:

public static int PreviousQuarter(DateTime? date = null)
{
    int[] previousQuarter = new[] {4, 4, 4, 1, 1, 1, 2, 2, 2, 3, 3, 3};
    return previousQuarter[(date ?? DateTime.Now.AddMonths(-3)).Month];
}