我需要根据字符串值执行检查是日期还是小数,但日期解析总是为十进制返回 true。
string val = "3.5";
DateTime oDate = DateTime.Parse(val);
Run Code Online (Sandbox Code Playgroud)
它返回一个有效的日期3/5/2019
。
当日期格式未知时,如何验证字符串以知道其有效日期?
如果你知道确切的表示,你可以做这样的事情:
format = "ddd dd MMM yyyy h:mm tt zzz";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
Run Code Online (Sandbox Code Playgroud)
如果你不知道,那么你就会被文化习俗所束缚
使用特定区域性的约定解析日期和时间字符串。Parse(String, IFormatProvider) 重载(请参阅解析和文化约定)
“如何验证字符串以了解其有效日期?”
问题是它"3.5"
被认为是有效日期(也是小数)。
如果您希望小数类型始终“获胜”(即您不希望isDate
和isDecimal
两者都是true
),请在验证中包含小数检查。
一种方法是使用方法TryParse
(bool
如果字符串可以解析为类型,则返回一个,并将参数设置out
为转换后的值)来确定字符串是否可以转换为类型,例如:
string val = "3.5";
// temp variables to hold parsed values
DateTime tmpDate;
decimal tmpDec;
int tmpInt;
var isDecimal = decimal.TryParse(val, out tmpDec);
var isInteger = int.TryParse(val, out tmpInt);
// When checking if it's a DateTime, make sure it's not also a decimal
var isDate = !isDecimal && DateTime.TryParse(val, out tmpDate);
Run Code Online (Sandbox Code Playgroud)