10

I have a string which has short month name in it.\

string month = "Jun";

I need to get month in digit from this month name.

Say i do this:

int monthInDigit = getMonth(month);

monthInDigit <-- 6

How can i achieve this. If you cant get my question pleases comment i will explain it proprly.

Thanxx in advance

Murtaza Munshi
  • 1,065
  • 4
  • 13
  • 40

3 Answers3

15
int monthInDigit = DateTime.ParseExact(month, "MMM", CultureInfo.InvariantCulture).Month;
Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
  • Why did u passed null as the last parameter – Murtaza Munshi Oct 07 '13 at 08:47
  • 1
    @ArsenMkrt: That's not true. If `DateTime.ParseExact` works depends on OP's current culture. If you pass `null` as third parameter you use `CultureInfo.CurrentCulture`. That's why i have used `CultureInfo.InvariantCulture` in my answer. Not every language abbreviates `June` with `Jun`. – Tim Schmelter Oct 07 '13 at 09:45
  • @TimSchmelter Thanxxx for the extra info and correcting the null paramter information. – Murtaza Munshi Oct 07 '13 at 09:57
9

You can parse it to a DateTime first:

DateTime dt = DateTime.ParseExact("Jun", "MMM", CultureInfo.InvariantCulture);
int month = dt.Month;
if(month < 6)
{  
    // do something...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

another way :

string [] arr= {jun, fab,...}; 

public int getMonth(string month){

for(int i = 0 ; i< arr.length ; i++){
   if(string[i].Contains(month) || month.Contains(arr[i]))
   return i+1;
   }

return -1;// if month is invalid , return -1
}
AmirHossein Rezaei
  • 1,086
  • 1
  • 16
  • 20