我正在尝试一种方法来检查是否正确插入了日,月和年。如果日期合适,则方法返回TRUE;如果日期不合适,则返回FALSE。 问题:代码总是返回false。
const int max_year = 2100;
const int min_year = 1900;
static bool CheckDate(int d, int m, int y)
{
if (d < 1 || d > 31)
{
if (m < 1 || m > 12)
{
if (y < min_year || y > max_year)
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
else
{
return true;
}
}
然后我要检查属性中的日期,例如:
public int Day
{
get
{
return day;
}
set
{
if (CheckDate(dan, mesec, year) == true)
{
day = value;
}
else
{
throw new Exception("Day is incorrect!");
}
}
}
答案 0 :(得分:2)
尽可能简单,只需将数字转换为字符串,然后执行yyyyMMdd格式的DateTime.TryParseExact
bool CheckDate(int y, int m, int d)
{
string t = $"{y:D4}{m:D2}{d:D2}";
return DateTime.TryParseExact(t, "yyyyMMdd", CultureInfo.InvariantCulture,DateTimeStyles.None, out DateTime dt);
}
当然,如果要限制有效年限,可以像在构建要解析的字符串之前一样,添加一个简单的逻辑来测试 y 变量。
if (y < min_year || y > max_year)
return false;
....
答案 1 :(得分:1)
我想指出您的属性设置器中可能存在的错误和/或错误的设计(这可能是您的“ 代码始终返回false ”的原因)。
如果仔细观察,会发现CheckDate
总是使用参数dan
,mesec
和year
来调用。如您所知,value
是要设置的值(Day = 1
或Day = 500
),但它不是CheckDate
调用的一部分。
如果这是您的目的,我可以说这是非常糟糕的设计。您应该直接在代码中调用CheckDate
,而不要使用几乎具有副作用的外观属性设置器。
public int Day
{
get
{
return day;
}
set
{
// Why this?
if (CheckDate(dan, mesec, year) == true)
{
day = value;
}
else
{
throw new Exception("Day is incorrect!");
}
}
}
答案 2 :(得分:-1)
或者您可以这样做:
static bool CheckDate(int d, int m, int y)
{
try
{
// This will throw an exception if the year, month or day are invalid
var temp = new DateTime(y, m, d);
return true;
}
except
{
return false;
}
}