windows 在 C# 中获取三个月(季度)代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5895873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get trimester (quarter) code in c#
提问by André
i needed to get the correspondent trimester (periods of 3 months, being the first trimester Jan, Feb and Mar) of a given date. Using the c# System.DateTime struct I didn't manage to find a method for what I was looking for. So I solved like this:
我需要获得给定日期的相应三个月(3 个月,即一月、二月和三月的前三个月)。使用 c# System.DateTime 结构我没有设法找到我正在寻找的方法。所以我是这样解决的:
DateTime sDeathDate = DateTime.Parse("18/09/1970");
int iDeathTrimester = Convert.ToInt32(Math.Round(Convert.ToDouble(sDeathDate.Month) / 3 + 0.25));
If someone knows a easier way to do this, please answer.
如果有人知道更简单的方法来做到这一点,请回答。
André
安德烈
回答by Patrick McDonald
Assuming Jan - Mar is trimester 1, Apr - Jun is trimester 2, Jul - Sep is Trimester 3 and Oct - Dec is trimester 4, then you can use
假设 1 月 - 3 月是第 1 学期,4 月 - 六月是第 2 学期,7 月 - 9 月是第 3 学期,10 月 - 12 月是第 4 学期,那么您可以使用
int trimester = (sDeathDate.Month - 1) / 3 + 1
This is the same as a quarter, did you mean something different?
这与四分之一相同,您的意思是不同的吗?
回答by il_guru
Math.CeilingReturns the smallest integer greater than or equal to the specified number.
Math.Ceiling返回大于或等于指定数字的最小整数。
DateTime sDeathDate = DateTime.Parse("18/11/1970");
int trimester = (int)Math.Ceiling(sDeathDate.Month/3.0);
Note that the code use 3.0to perform a floating point division and not an integer division
请注意,代码使用3.0执行浮点除法而不是整数除法
回答by André
The Time Period Library for .NETincludes the class Quarter(period of 3 months):
.NET的时间段库包括类Quarter(3 个月的时间段):
// ----------------------------------------------------------------------
public void QuarterOfDateSample()
{
DateTime moment = new DateTime( 1970, 9, 15 );
Console.WriteLine( "Quarter : {0}", new Quarter( moment ) );
// > Quarter : Q3 1970; 01.07.1970- 30.09.1970| 91.23:59
Console.WriteLine( "Quarter : {0}", new Quarter( 2006, YearQuarter.First ) );
// > Quarter : Q1 2006; 01.01.2006 - 31.03.2006 | 89.23:59
} // QuarterOfDateSample
回答by Amedio
If you use Math.Round (Double, MidpointRounding)you can do the round better without adding 0,25
如果您使用Math.Round (Double, MidpointRounding),您可以在不添加的情况下更好地完成回合0,25
See you
再见