valid date check with DateTime.TryParse method

亡梦爱人 提交于 2019-11-30 12:39:01

You could use the TryParseExact method which allows you to pass a collection of possible formats that you want to support. The TryParse method is culture dependent so be very careful if you decide to use it.

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.

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.

For more informations and the use with the time, you can check the MSDN Documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!