Thursday, September 4, 2008

C# Ordinal Number for a Month

I was parsing this page and I was trying to convert the following date into Datetime format:

Friday 5th of September, 2008

What I thought would end up being something readily available and easy turned out not the case. The biggest issue was "September" and I had to create a procedure to get the Ordinal number with a winding routine that finally did the job for me, although have to say it was alot bigger than I expected.

To call the function it's simply:

DateTime SelDate = ConvertLongDateStr(DateStr);

Below are the routines:


private static int GetMonthsNumber(string monthname,ref bool valid)
{
for (int month = 1; month < 13; month++)
{
DateTime date = new DateTime(1900, month, 1);
if (date.ToString("MMMM").ToUpper() == (monthname.ToUpper()))
{
valid = true;
return month;
}
}
valid = false;
return 0;
}

public DateTime ConvertLongDateStr(string LongDateStr)
{
// Thursday 4th of September, 2008 //
string DoW = LongDateStr.Substring(0,LongDateStr.IndexOf(" "));
LongDateStr = LongDateStr.Remove(0, LongDateStr.IndexOf(" ")+1);
// for loop for max of 2 integers //
string daystr = "";
for (int i=0;i<=1;i++)
{
try
{
int num = Int32.Parse(LongDateStr.Substring(0,1));
daystr = daystr+LongDateStr.Substring(0,1);
LongDateStr = LongDateStr.Remove(0,1);
}
catch (Exception)
{
// nothing required here //
}

}
LongDateStr = LongDateStr.Remove(0, LongDateStr.IndexOf(" ")+1); // removes "th" "st" "rd"
LongDateStr = LongDateStr.Remove(0, LongDateStr.IndexOf(" ")+1); // removes "of"
string LongMonthStr = LongDateStr.Substring(0,LongDateStr.IndexOf(","));
bool validmonth = false;
int MonthsVal = GetMonthsNumber(LongMonthStr,ref validmonth);
LongDateStr = LongDateStr.Remove(0, LongDateStr.IndexOf(" ")+1); // removes ","
string YearStr = LongDateStr.Trim();
string ShortDateStr = daystr+"-"+MonthsVal.ToString()+"-"+YearStr;
DateTime ShortDateVal = Convert.ToDateTime(ShortDateStr);
return ShortDateVal;
}

No comments: