Friday, August 27, 2010

DateTime.ParseExact

So after never having had CultureInfo.CurrentCulture on my radar, I ended up using it twice this week.

For the first use, see my previous post on ToUpperInvariant().

Today, I ran into a problem where I tried DateTime.Parse on a string which I had generated in a gridview using:

<asp:BoundField DataField="DateStarted"
  DataFormatString="{0:ddd MMM d hh:mmtt}" />
The compiler couldn't parse it.

I ended up having to decode it using the following:

DateTime dateCreated =DateTime.ParseExact(sdateCreated,
  "ddd MMM d hh:mmtt", CultureInfo.InvariantCulture);

ToUpperInvariant()

Whoa! Jon Skeet answered a question of mine on StackOverflow this week! I am honored.

The question was:

In C# what is the difference between ToUpper() and ToUpperInvariant()?

And the answer was, in a nutshell, "Unless you are programming in Turkish, no difference."

What brought me to ask that question started with a need to always reformat user input for first and last name with Initial Letter Case: first letter capitalized, rest lower case. (I know, I know, this is not all last names follow this convention, but hey, I didn't define the user requirements.) (In word I use Shift-F3 all the time.)

So I went looking in intellisense for a string method called InitialLetterCase(). After all, there are string methods ToUpper() and ToLower().

There was no InitialLetterCase() method, but I found ToUpperInvariant(). What did that do? I did a google search but the first few hits didn't seem to answer the question.

So thank you, Jon Skeet and StackOverflow, for the answer.

FYI, the solution to my request is a simple

tbFirstName.Text =
CultureInfo.CurrentCulture.TextInfo.ToTitleCase(tbFirstName.Text); :