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

Calculating the previous quarter from the current Month in C#

我确定有更简洁的方法可以达到这个结果?但是,我创建了以下方法来计算当前月份或传入的 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.");
    }
}

这应该可以解决问题

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);
}
private int PreviousQuarter(DateTime date)
{
        return (int)Math.Ceiling((double)date.AddMonths(-3).Month / (double)3);
}

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

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];
}