输入年月日,得到输入的日期是该年的第多少天
记录一下自己的代码
#region 让用户输入一个年月日,输出这一天是该年的第几天
static void Day()
{
Console.WriteLine("请输入年份:");
var year = Console.ReadLine();
var resYear = IsInt(year);
while (resYear < 1000 || resYear > 9999)
{
Console.WriteLine("年份输入有误(输入的年份应为1000-9999之间,且不为小数)");
Console.WriteLine("请输入年份:");
year = Console.ReadLine();
resYear = IsInt(year);
}
Console.WriteLine("请输入月份:");
var mouth = Console.ReadLine();
int resMouth = IsInt(mouth);
while (resMouth < 1 || resMouth > 12)
{
Console.WriteLine("月份输入有误(输入的月份应为1-12,且不为小数)");
Console.WriteLine("请输入月份:");
mouth = Console.ReadLine();
resMouth = IsInt(mouth);
}
Console.WriteLine("请输入天:");
var day = Console.ReadLine();
int resDay = IsInt(day);
if (resYear % 4 == 0 && resYear % 100 != 0 || resYear % 400 == 0)
{
if (resMouth == 2)
{
while (resDay < 1 || resDay > 29)
{
Console.WriteLine("天数输入有误(输入的天数应为1-29,且不为小数)");
Console.WriteLine("请输入天数:");
day = Console.ReadLine();
resDay = IsInt(day);
}
}
else if (resMouth == 1 || resMouth == 3 || resMouth == 5 || resMouth == 7 || resMouth == 8 || resMouth == 10 || resMouth == 12)
{
while (resDay < 1 || resDay > 31)
{
Console.WriteLine("天数输入有误(输入的天数应为1-31,且不为小数)");
Console.WriteLine("请输入天数:");
day = Console.ReadLine();
resDay = IsInt(day);
}
}
else
{
while (resDay < 1 || resDay > 30)
{
Console.WriteLine("天数输入有误(输入的天数应为1-30,且不为小数)");
Console.WriteLine("请输入天数:");
day = Console.ReadLine();
resDay = IsInt(day);
}
}
}
else
{
if (resMouth == 2)
{
while (resDay < 1 || resDay > 28)
{
Console.WriteLine("天数输入有误(输入的天数应为1-28,且不为小数)");
Console.WriteLine("请输入天数:");
day = Console.ReadLine();
resDay = IsInt(day);
}
}
else if (resMouth == 1 || resMouth == 3 || resMouth == 5 || resMouth == 7 || resMouth == 8 || resMouth == 10 || resMouth == 12)
{
while (resDay < 1 || resDay > 31)
{
Console.WriteLine("天数输入有误(输入的天数应为1-31,且不为小数)");
Console.WriteLine("请输入天数:");
day = Console.ReadLine();
resDay = IsInt(day);
}
}
else
{
while (resDay < 1 || resDay > 30)
{
Console.WriteLine("天数输入有误(输入的天数应为1-30,且不为小数)");
Console.WriteLine("请输入天数:");
day = Console.ReadLine();
resDay = IsInt(day);
}
}
}
int days = 0;//用来记录输入的日期是多少天
switch (resMouth - 1)//resMouth-1 求输入月份前边月份的天数最大为12
{
case 1:
days += 31;
break;
case 2:
if (resYear % 4 == 0 && resYear % 100 != 0 || resYear % 400 == 0)
{
days += 29;
}
else
{
days += 28;
}
goto case 1;
case 3:
days += 31;
goto case 2;
case 4:
days += 30;
goto case 3;
case 5:
days += 31;
goto case 4;
case 6:
days += 30;
goto case 5;
case 7:
days += 31;
goto case 6;
case 8:
days += 31;
goto case 7;
case 9:
days += 30;
goto case 8;
case 10:
days += 31;
goto case 9;
case 11:
days += 30;
goto case 10;
}
days += resDay;
Console.WriteLine("您输入的年份为:{0},月份为:{1},天数为:{2},在该年为第{3}天。", year, mouth, day, days);
}
/// <summary>
/// 输入一个字符串,判断该字符串能否转换为int类型,失败返回0 成功返回成功的值
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
static int IsInt(string num)
{
int result;
int.TryParse(num, out result);
return result;
}
#endregion