需要使用TryParse解析dd.MM.yyyy到DateTime [英] Need parse dd.MM.yyyy to DateTime using TryParse
问题描述
我需要解析字符串到DateTime。字符串总是以以下格式
10.10.2010这意味着dd.MM.yyyy,用点分隔。
我想使用DateTime.TryParse或任何其他方法。请建议。
更新
更新了这个问题。我只是寻找正确的方法来实现目标。
不手动解析
TryParse
您指定格式 - 但您可以使用 TryParseExact
:
DateTime date;
/ pre>
if(DateTime.TryParseExact(text,dd'。'MM'。'yyyy,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
else
{
//解析失败
}
请注意,该点不需要用引号进行转义,但是我个人希望将任何文字文本放在引号中,以确保它不会改变这是一个个人喜好的事情,虽然 - 你当然可以使用dd.MM.yyyy如果你想要。
同样,我指定了不变的文化,这是我通常要做一个固定的自定义风格 - 但是你可以使它使用当前的文化或特定的其他文化,如果你想要的。当您使用自定义样式(而不是诸如长日期等标准样式)时,不太可能有任何区别。
I need to parse string to DateTime. The string is always in the following format
"10.10.2010" That means dd.MM.yyyy, separated with dots.
I want to use DateTime.TryParse or any other method. Please suggest.
UPDATE
Updated the question. I am just looking for the right method to achieve the goal. Not manual parsing
解决方案
TryParse
doesn't let you specify the format - but you can useTryParseExact
:DateTime date; if (DateTime.TryParseExact(text, "dd'.'MM'.'yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { // Success } else { // Parse failed }
Note that the dot doesn't strictly need to be escaped with the quotes, but personally I like to put any literal text in quotes just to make sure that it won't be changed. It's a personal preference thing though - you could certainly just use "dd.MM.yyyy" if you wanted.
Likewise I've specified the invariant culture which is what I normally do for a fixed custom style - but you could make it use the current culture or a specific other culture if you wanted. When you're using a custom style (rather than a standard style such as "long date") it's less likely to make any difference, admittedly.
这篇关于需要使用TryParse解析dd.MM.yyyy到DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!