day month year problem
Hello everybody, I am having a problem to solve the following c# exercise: February can be 29 days if it is during a leap year. Do NOT change the implementation of date_convert. Instead, add additional code in your main so that before you display the output of the method, if the month entered by the user is February, prompt the user for the year, and then use IsLeap to check the year and adjust the output of date_convert accordingly. Write appropriate method calls and statements within your main so that the console session may look as follows: A valid console session may look as follows: Please enter a month: March The number of days in March is 31 Another session may look as follows: Please enter a month: february Please enter a year: 2007 The number of days in February is 28 Another session may look as follows: Please enter a month: february Please enter a year: 2000 The number of days in February is 29 If anybody can help me to solve the problem then i will be very greatfull. Syed
Jan MontanoPosted Apr 6, 2009, 10:13 PM
private const int DEFAULT_YEAR = 2000;
static void Main(string[] args)
{
Console.WriteLine("Please enter a month: ");
string month = Console.ReadLine();
int formattedMonth = ConvertMonth(month);
int daysInMonth = 0;
if (formattedMonth > 0) // this is a valid month
{
if (month.ToLower() == "february")
{
Console.WriteLine("Please enter a year: ");
int year = Convert.ToInt32(Console.ReadLine());
daysInMonth = DateTime.DaysInMonth(year, formattedMonth);
}
else
{
daysInMonth = DateTime.DaysInMonth(DEFAULT_YEAR, formattedMonth);
}
Console.WriteLine(string.Format("The number of days in {0} is {1}", month, daysInMonth));
Console.ReadLine();
}
}
static int ConvertMonth(string month)
{
int formattedMonth = 0;
DateTime dummyDate;
if (DateTime.TryParse(month.Trim() + " 1, 2000", out dummyDate))
{
formattedMonth = dummyDate.Month;
}
return formattedMonth;
}