다음과 같은 문제가 있습니다.다음 8 월 찾기 방법? C#
다음 8 월을 찾아야합니다. 나는 다른 말로하면 2009-09-01 우리는 2010-08-31이 필요하다 2009-06-21 우리는 2009-08-31이 필요하다.
오늘 제가 8 월 31 일보다 작은 지 확인할 수 있지만 다른 가능성이 있는지 궁금합니다.
다음과 같은 문제가 있습니다.다음 8 월 찾기 방법? C#
다음 8 월을 찾아야합니다. 나는 다른 말로하면 2009-09-01 우리는 2010-08-31이 필요하다 2009-06-21 우리는 2009-08-31이 필요하다.
오늘 제가 8 월 31 일보다 작은 지 확인할 수 있지만 다른 가능성이 있는지 궁금합니다.
public static class DateTimeExtensions
{
public static DateTime GetNextAugust31(this DateTime date)
{
return new DateTime(date.Month <= 8 ? date.Year : date.Year + 1, 8, 31);
}
}
닷넷 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);
}
}
이 작동
이것은 실제로 올바르지 않습니다. 8 월이 아닌 입력일을 반환합니다. 방법에 어떤 달이 보내 졌을 지 알 것입니다. – BFree
일할 확률이 12 회 1이 었음 :) 이제 0.2 년 내내 –
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");
}
}
. 예외 처리를 추가하십시오. 예를 들어 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();
}
다음으로 우리는 int를 증가시키는 방법을 묻습니다. –