简体   繁体   English

使用DateTime.TryParse方法检查有效日期

[英]valid date check with DateTime.TryParse method

I am using Datetime.TryParse method to check the valid datetime. 我正在使用Datetime.TryParse方法来检查有效的日期时间。 the input date string would be any string data. 输入日期字符串将是任何字符串数据。 but is returning false as the specify date in invalid. 但是返回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.... 欢迎任何建议......

You could use the TryParseExact method which allows you to pass a collection of possible formats that you want to support. 您可以使用TryParseExact方法,该方法允许您传递要支持的可能格式的集合。 The TryParse method is culture dependent so be very careful if you decide to use it. 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
}

You should be using TryParseExact as 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);

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文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM