我需要解析字符串日期时间。该字符串总是以下面的格式
I need to parse string to DateTime. The string is always in the following format
10.10.2010这意味着DD.MM.YYYY,用点分隔。
"10.10.2010" That means dd.MM.yyyy, separated with dots.
我想使用DateTime.TryParse或任何其它方法。请建议。
I want to use DateTime.TryParse or any other method. Please suggest.
更新
更新的问题。我只是在寻找合适的方法来实现这一目标。 不是手动解析
Updated the question. I am just looking for the right method to achieve the goal. Not manual parsing
的TryParse
并没有让你指定的格式 - 但你可以使用的 TryParseExact
:
TryParse
doesn't let you specify the format - but you can use TryParseExact
:
DateTime date;
if (DateTime.TryParseExact(text, "dd'.'MM'.'yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
else
{
// Parse failed
}
请注意,该点并不严格需要用引号进行转义,但我个人喜欢把引号中任意文字只是为了确保它不会被改变。这是一个个人的preference东西虽然 - 你当然可以只使用DD.MM.YYYY如果你想
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.