C# 使用 DateTime.TryParse 方法检查有效日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11310439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
valid date check with DateTime.TryParse method
提问by Sujit
I am using Datetime.TryParsemethod to check the valid datetime. the input date string would be any string data. but is returning false as the specify date in invalid.
我正在使用Datetime.TryParse方法来检查有效的日期时间。输入日期字符串可以是任何字符串数据。但返回 false 作为指定日期无效。
DateTime fromDateValue;
if (DateTime.TryParse("15/07/2012", out fromDateValue))
{
//do for valid date
}
else
{
//do for in-valid date
}
Edit:i missed. i need to check the valid date with time as "15/07/2012 12:00:00".
编辑:我错过了。我需要检查有效日期和时间为“15/07/2012 12:00:00”。
Any suggestions are welcome....
欢迎任何建议......
采纳答案by Darin Dimitrov
You could use the TryParseExactmethod which allows you to pass a collection of possible formats that you want to support. The TryParsemethod is culture dependent so be very careful if you decide to use it.
您可以使用TryParseExact方法,该方法允许您传递您想要支持的可能格式的集合。该TryParse方法取决于文化,因此如果您决定使用它,请务必小心。
So for example:
例如:
DateTime fromDateValue;
string s = "15/07/2012";
var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
{
// do for valid date
}
else
{
// do for invalid date
}
回答by V4Vendetta
You should be using TryParseExactas you seem to have the format fixed in your case.
您应该使用,TryParseExact因为您似乎已经在您的情况下修复了格式。
Something like can also work for you
类似的东西也可以为你工作
DateTime.ParseExact([yourdatehere],
new[] { "dd/MM/yyyy", "dd/M/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
回答by Gianni B.
As the others said, you can use TryParseExact.
正如其他人所说,您可以使用TryParseExact.
For more informations and the use with the time, you can check the MSDN Documentation
有关更多信息和使用时间,您可以查看MSDN 文档

