Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need parse dd.MM.yyyy to DateTime using TryParse

Tags:

c#

.net

datetime

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

like image 251
Captain Comic Avatar asked Oct 19 '10 10:10

Captain Comic


People also ask

What is DateTime TryParse?

TryParse(String, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

How do you check if the date is in dd mm yyyy format in C #?

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


1 Answers

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.

like image 62
Jon Skeet Avatar answered Sep 27 '22 21:09

Jon Skeet