Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ToTitleCase and text-formatted dates/times

I have a string "THURSDAY 26th JANUARY 2011".

When I format this using CultureInfo.ToTitleCase():

var dateString = "THURSDAY 26th JANUARY 2011";
var titleString = myCultureInfoObject.TextInfo.ToTitleCase(dateString);

It is displayed like this: "Thursday 26Th January 2011". This is exactly what I need...except the T in 26Th has been capitalised. Is there any way to stop this from happening as it is a date and looks wrong? I.e only title-casing characters that don't have a number directly before them?

like image 585
harman_kardon Avatar asked Jan 25 '12 16:01

harman_kardon


1 Answers

You could use a regex with a MatchEvaluator to put only "real" words in title case:

var dateString = "THURSDAY 26th JANUARY 2011";
MatchEvaluator ev = m => myCultureInfoObject.TextInfo.ToTitleCase(m.Value);
var titleString = Regex.Replace(dateString, @"\b[a-zA-Z]+\b", ev);

This will apply title case only to "THURSDAY" and "JANUARY", but not "26TH" because it doesn't match the regex pattern.

like image 150
Thomas Levesque Avatar answered Oct 30 '22 18:10

Thomas Levesque