开发者

How to check whether date is in mm/DD/yyyy format or not in C#

开发者 https://www.devze.com 2023-02-04 04:17 出处:网络
How do开发者_如何学运维 I check whether a date is in mm/DD/yyyy format or not in C#?Note: I\'m assuming that you were asking whether a string is a valid date in \"MM/dd/yyyy\" format. A DateTime itsel

How do开发者_如何学运维 I check whether a date is in mm/DD/yyyy format or not in C#?


Note: I'm assuming that you were asking whether a string is a valid date in "MM/dd/yyyy" format. A DateTime itself doesn't have a format, so you can't check that.

Use DateTime.TryParseExact to try to parse it:

string text = "02/25/2008";
DateTime parsed;

bool valid = DateTime.TryParseExact(text, "MM/dd/yyyy",
                                    CultureInfo.InvariantCulture,
                                    DateTimeStyles.None,
                                    out parsed);

Note that I've changed your format string to what I think you mean - I doubt that you really meant the first bit to be minutes, for example.

If you don't want the invariant culture, specify a different one :)

0

精彩评论

暂无评论...
验证码 换一张
取 消