Wednesday, June 24, 2009

ShortDatePattern with MMM

I wanted date printed with the given culture format but to print month name instrad of month number like Jan instead of 01 in en-us, I tried this with few combination and DateTimeFormat along with RegEx came into rescue. here is the code.

DateTime date = DateTime.Today; // Take a date to display in given format.
CultureInfo culture = CultureInfo.GetCultureInfo("en-us"); // get a random calture.
string datePattern = culture.DateTimeFormat.ShortDatePattern; // get short date format

datePattern = Regex.Replace(datePattern, "(?i)[m]+", "MMM"); // replace Month natation for MMM to get 3 char long month name
Console.WriteLine(date.ToString(datePattern,culture)); // print date in given format

datePattern = Regex.Replace(datePattern, "(?i)[m]+", "MMMM"); // replace Month natation for MMMM to get full month name.
Console.WriteLine(date.ToString(datePattern, culture));


Cheers!!!
Pradeep