我有以下问题:
我们需要找到下一个八月。换句话说,如果我们是2009-09-01,我们需要2010-08-31如果我们是2009-06-21我们需要2009-08-31。
我知道我可以检查今天是否小于8月31日,但我想知道是否还有其他可能性。
答案 0 :(得分:16)
public static class DateTimeExtensions
{
public static DateTime GetNextAugust31(this DateTime date)
{
return new DateTime(date.Month <= 8 ? date.Year : date.Year + 1, 8, 31);
}
}
答案 1 :(得分:2)
.Net 2.0
DateTime NextAugust(DateTime inputDate)
{
if (inputDate.Month <= 8)
{
return new DateTime(inputDate.Year, 8, 31);
}
else
{
return new DateTime(inputDate.Year+1, 8, 31);
}
}
答案 2 :(得分:1)
public static DateTime NextAugust(DateTime input)
{
switch(input.Month.CompareTo(8))
{
case -1:
case 0: return new DateTime(input.Year, 8, 31);
case 1:
return new DateTime(input.Year + 1, 8, 31);
default:
throw new ApplicationException("This should never happen");
}
}
答案 3 :(得分:1)
这很有效。一定要添加一些异常处理。例如,如果您为feb传入31,则会抛出异常。
/// <summary>
/// Returns a date for the next occurance of a given month
/// </summary>
/// <param name="date">The starting date</param>
/// <param name="month">The month requested. Valid values (1-12)</param>
/// <param name="day">The day requestd. Valid values (1-31)</param>
/// <returns>The next occurance of the date.</returns>
public DateTime GetNextMonthByIndex(DateTime date, int month, int day)
{
// we are in the target month and the day is less than the target date
if (date.Month == month && date.Day <= day)
return new DateTime(date.Year, month, day);
//add month to date until we hit our month
while (true)
{
date = date.AddMonths(1);
if (date.Month == month)
return new DateTime(date.Year, month, day);
}
}
private void Form1_Load(object sender, EventArgs e)
{
DateTime d = DateTime.Now;
//get the next august
Text = GetNextMonthByIndex(d, 8, 31).ToString();
}