我需要验证某些变量是否可以创建有效的日期时间,如果可以,则在不抛出异常的情况下忽略它。
我有以下代码
int y, m, d, h, mi, s, tz;
ogrFeature.GetFieldAsDateTime(field, out y, out m, out d, out h, out mi, out s, out tz);
fdr[fdrIndex++] = new DateTime(y, m, d, h, mi, s);
如果(来自 MSDN),目前日期时间的构造将失败
year is less than 1 or greater than > 9999.
month is less than 1 or greater than> 12.
day is less than 1 or greater than the> number of days in month.
hour is less than 0 or greater than> 23.
minute is less than 0 or greater than> 59.
second is less than 0 or greater than> 59.
millisecond is less than 0 or greater> than 999.
我查了一下,似乎没有任何特定的方法来验证这种输入。
有没有一种很好的方法来验证这个输入,而不必有一大堆 ifs 或将其包装在讨厌的 try/catch 中并捕获 ArgumentOutOfRangeException?
请您参考如下方法:
你可以使用这个方法:
public static DateTime? GetFieldAsDateTime(int y, int m, int d,
int h, int mi, int s)
{
DateTime result;
var input =
string.Format("{0:000#}-{1:0#}-{2:0#}T{3:0#}:{4:0#}:{5:0#}",
y, m, d, h, mi, s);
if (DateTime.TryParse(input, CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.RoundtripKind, out result))
{
return result;
}
return null;
}
