我如何发现给定日期的四分之一

以下是一个财政年度的宿舍

April to June - Q1 July to Sep - Q2 Oct to Dec - Q3 Jan to March - Q4 

如果输入日期的月份如上所述,我需要以季度数表示输出。

例如,

如果我给出输入日期(比如1月2日 ),我需要输出为Q4

如果我输入( 6月5日 ),输出应该给Q1

根据输入日期,我需要季度编号。

你可以简单地写一个方法

 public static int GetQuarter(DateTime date) { if (date.Month >= 4 && date.Month <= 6) return 1; else if (date.Month >= 7 && date.Month <= 9) return 2; else if (date.Month >= 10 && date.Month <= 12) return 3; else return 4; } 

如果您更喜欢没有分支和数组的简短解决方案,这是我的首选解决方案。

正常季度:

 public static int GetQuarter(this DateTime date) { return (date.Month + 2)/3; } 

财政年度季度:

 public static int GetFinancialQuarter(this DateTime date) { return (date.AddMonths(3).Month + 2)/3; } 

整数除法将截断小数,为您提供整数结果。 将方法放入静态类中,您将使用扩展方法,如下所示:

 date.GetQuarter() date.GetFinancialQuarter() 

这是“正常年份”。 我想你可以调整样本:

 string.Format("Q{0}", (date.Month + 2)/3); 
 public static int GetQuarter(DateTime date) { int[] quarters = new int[] { 4,4,4,1,1,1,2,2,2,3,3,3 }; return quarters[date.Month-1]; } 

实现这一目标的最简单一致的方法:


定期

 Math.Ceiling(date.Month / 3.0) 

财政(刚刚向上移动了2 + 1个季度)

 Math.Ceiling(date.Month / 3.0 + 2) % 4 + 1 

 01.01.2016 00:00:00 -> Q1 -> FQ4 01.02.2016 00:00:00 -> Q1 -> FQ4 01.03.2016 00:00:00 -> Q1 -> FQ4 01.04.2016 00:00:00 -> Q2 -> FQ1 01.05.2016 00:00:00 -> Q2 -> FQ1 01.06.2016 00:00:00 -> Q2 -> FQ1 01.07.2016 00:00:00 -> Q3 -> FQ2 01.08.2016 00:00:00 -> Q3 -> FQ2 01.09.2016 00:00:00 -> Q3 -> FQ2 01.10.2016 00:00:00 -> Q4 -> FQ3 01.11.2016 00:00:00 -> Q4 -> FQ3 01.12.2016 00:00:00 -> Q4 -> FQ3 

结果是介于1和4之间的值。几乎任何环境都具有CEILfunction,因此这也适用于任何语言。

 int CurrentQuarter = (int)Math.Floor(((decimal)DateTime.Today.Month + 2) / 3); 

或将DateTime.Today更改为所需日期。

扩展方法和较少的比较:

 public static class DateTimeExtension { public static int GetQuarter(this DateTime dateTime) { if (dateTime.Month <= 3) return 1; if (dateTime.Month <= 6) return 2; if (dateTime.Month <= 9) return 3; return 4; } } 

在sql中,它很简单

 ((((month(@mydate)-1)/3)+3) % 4) + 1 

检查一下:

 declare @mydate datetime set @mydate = '2011-01-01' while @mydate <= '2011-12-31' begin print ((((month(@mydate)-1)/3)+3) % 4) + 1 set @mydate = dateadd(month, 1, @mydate) end 

或者如果你想在.net中这样做,就像

 String.Format("Q{0}", ((((date.Month-1)/3)+3) % 4) + 1); 

你可以这样做:

 for (int i = 1; i <= 12; i++) { Console.WriteLine("Month {0} - Q{1}", i, Math.Ceiling((i <= 3 ? 12 - i + 1 : i - 3) / 3M)); } 

输出将是: 在此处输入图像描述

此方法允许您指定季度的开始月份,并提供整个期间的年份。

  public string GetQuarterPeriod(DateTime date, int quarterStartMonth) { var quarterDateOffset = date.AddMonths(1 - quarterStartMonth); return $"Q{Math.Ceiling((decimal)quarterDateOffset.Month / 3)} {quarterDateOffset.Year}" + (quarterStartMonth == 1 ? "" : $"/{quarterDateOffset.Year + 1}"); } 

赠送:

 GetQuarterPeriod(new DateTime(2018, 4, 1), 4) -> "Q1 2018/2019" GetQuarterPeriod(new DateTime(2018, 1, 1), 1) -> "Q1 2018" 

函数说明如果月份是1月(1),则它被限制为一年。