using System;
namespace NextDateLib
{
/// <summary>
/// 求解下一天的日期
/// </summary>
public class NextDate
{
private MyDate _myDate;
#region 属性
/// <summary>
/// 设置当前日期
/// </summary>
public MyDate CurrentDate {
get { return _myDate; }
set { _myDate = value; }
}
#endregion
#region 构造函数
public NextDate(MyDate myDate)
{
_myDate = myDate;
}
public NextDate (int year,int month,int day)
{
_myDate = new MyDate(year,month,day);
}
#endregion
/// <summary>
/// 判断给定的年份是不是闰年
/// </summary>
/// <param name="year">4位的年份,例如:2012</param>
/// <returns>True:是闰年,False:非闰年</returns>
public bool IsLeapYear(int year)
{
bool bIsLeap = false;
if(year %4 ==0 && year % 100 !=0)
bIsLeap = true;
return bIsLeap;
}
/// <summary>
/// 返回下一日期
/// </summary>
/// <returns>下一日期</returns>
public MyDate NextDate1()
{
// tomorrowDay, tomorrowMonth, tomorrowYear: indicate date of next day
int tomorrowDay, tomorrowMonth, tomorrowYear;
int tempMonth;// indicate equivalence class of "month"
// Initialize tomorrow's date
tomorrowDay = _myDate.Day;
tomorrowMonth =_myDate.Month;
tomorrowYear = _myDate.Year;
// Get equivalence class of "month"
if( _myDate.Month==1 || _myDate.Month==3 ||
_myDate.Month==5 || _myDate.Month==7 ||
_myDate.Month==8 || _myDate.Month==10 )
tempMonth = 1;// month has 31 days
else if( _myDate.Month == 12 )
tempMonth = 3;// month is the last month of the year
else if( _myDate.Month == 2 )
tempMonth = 4;// month has 28 days or 29 days
else
tempMonth = 2;// month has 30 days
bool bValid = true;// indicate whether the input is a valid date
switch( tempMonth ){
case 1: if( _myDate.Day < 31 )
tomorrowDay = _myDate.Day + 1;
else
{// the last day of the month
tomorrowDay = 1;
tomorrowMonth = _myDate.Month + 1;
}
break;
case 2: if( _myDate.Day < 30 )
tomorrowDay = _myDate.Day + 1;
else if( _myDate.Day == 30 )
{
tomorrowDay = 1;
tomorrowMonth = _myDate.Month + 1;
}
else
{
bValid = false;
//strTomorrow.Format( "The month %d Can not have %d days.\n", month, day );
}
break;
case 3: if( _myDate.Day < 31 )// December
tomorrowDay = _myDate.Day + 1;
else// the last day of the year
{
tomorrowDay = 1;
tomorrowMonth = 1;
if( _myDate.Year == 2050 )
{
throw new Exception("Reach the last date");
}
else
tomorrowYear = _myDate.Year + 1;
}
break;
case 4: if( _myDate.Day < 28 )// February
tomorrowDay = _myDate.Day + 1;
else
{
if( _myDate.Day == 28 )
{
if( IsLeapYear( _myDate.Year ) )
tomorrowDay = 29;
else
{
tomorrowDay = 1;
tomorrowMonth = 3;
}
}
else if( _myDate.Day == 29 )
{
if( IsLeapYear( _myDate.Year ) )
{
tomorrowDay = 1;
tomorrowMonth = 3;
}
else
{
throw new Exception(_myDate.Year+ "年2月没有"+_myDate.Day+"号!");
}
}
else// Feb. only has at most 29 days
{
throw new Exception(_myDate.Year+ "年2月没有"+_myDate.Day+"号!");
}
}
break;
}
if( bValid )
{
MyDate _nextDate = new MyDate(tomorrowYear,tomorrowMonth,tomorrowDay);
return _nextDate;
}
else
throw new Exception("未知错误");
}
}
}