tags:

views:

106

answers:

5

Hi

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

+1  A: 

Why not use ParseExact instead?

var theDate = DateTime.ParseExact("dd.MM.yyyy", yourDateString, CultureInfo.InvariantCulture);
klausbyskov
-1 not quite - this can throw exceptions...
Dror
@Dror, if you read the question you will see this: "The string is always in the following format", which would mean that the OP could easily use ParseExact. And he could use a try catch block around it if necessary.
klausbyskov
Does not compile
Captain Comic
ParseExact is ok, but it takes at least three parameters
Captain Comic
He did also say "I want to use DateTime.TryParse" - the closest would be TryParseExact. removed down-vote
Dror
+4  A: 

Use the TryParseExact method:

DateTime parsed;
if (DateTime.TryParseExact(yourString, "dd'.'MM'.'yyyy",
    CultureInfo.CurrentCulture, DateTimeStyles.None, out parsed))
{
    // success
}
LukeH
`null` isn't a valid `DateTimeStyles` value.
Jon Skeet
@Jon: Yep, just realised that. Editing...
LukeH
+2  A: 

use DateTime.TryParseExact(...)

Itay
+5  A: 

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
}

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.

Jon Skeet
Cool, thank u Jon.
Captain Comic
+1  A: 

You can use DateTime.TryParseExact

Dror