gpt4 book ai didi

c# - 尝试编写我自己的日期程序,需要在 C# 中检查指定月份的最大日期

转载 作者:太空宇宙 更新时间:2023-11-03 11:02:38 24 4
gpt4 key购买 nike

我正在尝试用 C# 编写自己的 Date 程序,我遇到的问题是当用户输入日期(例如 2-31)时,程序允许输入。我想创建一个条件,我可以匹配输入的月份,然后从中查看该月的日期是否可用。我在下面使用这段代码,但它会抛出任何一天的异常,例如 10 月 10 日,这应该是正确的。如果我将其注释掉,日期有效,但它不会检查是否匹配月份。

public int Day
{
get
{
return day;
}
private set
{
//int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30,
// 31, 31, 30, 31, 30, 31 };

//// check if day in range for month
//if (value > 0 && value <= daysPerMonth[Month])
// day = value;

//else // day is invalid
// throw new ArgumentOutOfRangeException(
// "Day", value, "Day out of range for current month/year");

if (value > 0 && value <= 31)
day = value;
else
throw new ArgumentOutOfRangeException("Day", value, "Day must be 1-31");

}
}

最佳答案

您必须知道用户选择的月份和年份(以正确处理闰年)。

它必须是这样的:

public int Day
{
get
{
return day;
}
private set
{
var endOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
if (value > 0 && value <= endOfMonth.Day)
day = value;
else
{
var message = string.Format("Day must be between {0} and {1}", 1 endOfMonth.Day);
throw new ArgumentOutOfRangeException("Day", value, message);
}
}
}

其中 yearmonth 是您类(class)中的其他字段。如果您真的想在不引用 DateTime 类的情况下执行此操作,我建议将此逻辑提取到一个静态类中,该类可以进行数学运算而无需在您想要的任何时候重新编码该月的最后一天。

public static class DateHelper
{
private int[] daysInMonth = new[] { 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };

public static bool IsLeapYear(int year)
{
// TODO: taken from wikipedia, can be improved
if (year % 400 == 0)
return true;
else if (year % 100 == 0)
return false;
else if (year % 4 == 0)
return true;
return false;
}

public static bool GetDaysInMonth(int year, int month)
{
// TODO: check for valid ranges
var days = daysInMonth[month - 1];
if (month == 2 && IsLeapYear(year))
days++;
return days;
}
}

然后你可以像这样使用它:

public int Day
{
get
{
return day;
}
private set
{
var endOfMonth = DateHelper.GetDaysInMonth(year, month);
if (value > 0 && value <= endOfMonth)
day = value;
else
{
var message = string.Format("Day must be between {0} and {1}", 1 endOfMonth);
throw new ArgumentOutOfRangeException("Day", value, message);
}
}
}

关于c# - 尝试编写我自己的日期程序,需要在 C# 中检查指定月份的最大日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17120160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com