在c#中,我想要一个函数来获取当前日期并返回一年中该季度的最后一个月的数字(作为2个字符的字符串)
所以
类似的东西:
DateTime dt = new DateTime(
DateTime.Today.Year,
DateTime.Today.Month,
DateTime.Today.Day);
String 2characterlastMonthinQuarter = CalcLastMonthInQuarter(dt);
答案 0 :(得分:7)
public static int CalcLastMonthInQuarter(DateTime dt)
{
return 3 * ((dt.Month - 1) / 3 + 1);
}
public static string CalcLastMonthInQuarterStr(DateTime dt)
{
return CalcLastMonthInQuarter(dt).ToString("00");
}
这里,这个测试:
for(int month = 1; month <= 12; ++month)
{
Console.WriteLine("{0}: {1}", month, CalcLastMonthInQuarterStr(new DateTime(2011, month, 1)));
}
打印:
1: 03
2: 03
3: 03
4: 06
5: 06
6: 06
7: 09
8: 09
9: 09
10: 12
11: 12
12: 12
答案 1 :(得分:3)
我假设标准的季末结束日期。我强烈不喜欢在这里做丑陋的算术。它更具可读性和可维护性。即:
public static string LastMonthOfQuarterAsString(DateTime date) {
return String.Format("{0:00}", LastMonthOfQuarter(date));
}
private static int LastMonthOfQuarter(DateTime date) {
int year = date.Year;
DateTime[] endOfQuarters = new[] {
new DateTime(year, 3, 31),
new DateTime(year, 6, 30),
new DateTime(year, 9, 30),
new DateTime(year, 12, 31)
};
DateTime quarterEndForDate = endOfQuarters.First(d => date <= d);
return quarterEndForDate.Month;
}
答案 2 :(得分:2)
((DateTime.Now.Month + 2) / 3 * 3)
答案 3 :(得分:0)
public static String CalcLastMonthInQuarter(DateTime dt)
{
return (Math.Ceiling(dt.Month / 3D) * 3).ToString("00");
}