有效的日期检查与DateTime.TryParse方法 [英] valid date check with DateTime.TryParse method

查看:2954
本文介绍了有效的日期检查与DateTime.TryParse方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Datetime.TryParse 方法来检查有效的日期时间。输入日期字符串将是任何字符串数据。但是返回false作为指定日期无效。

I am using Datetime.TryParse method 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 fromDateValue;
if (DateTime.TryParse("15/07/2012", out fromDateValue))
{
    //do for valid date
}
else
{
    //do for in-valid date
}

编辑:我错过了我需要查看有效日期为15/07/2012 12:00:00。

i missed. i need to check the valid date with time as "15/07/2012 12:00:00".

欢迎任何建议....

Any suggestions are welcome....

推荐答案

您可以使用 TryParseExact 方法,允许您传递要支持的可能格式的集合。 TryParse 方法是文化依赖的,所以如果您决定使用它,请非常小心。

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.

所以例如: / p>

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
}

这篇关于有效的日期检查与DateTime.TryParse方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆