gpt4 book ai didi

c# - TryParse 来自单个时间元素的日期时间

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

我需要验证某些变量是否可以创建有效的日期时间,如果可以,则在不抛出异常的情况下忽略它。

我有以下代码

 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;
}

关于c# - TryParse 来自单个时间元素的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6591559/

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