views:

58

answers:

4

I have a column called Month in a stored proc which returns to me the month in string name terms (eg. January, Febuary, March etc.)

I would like to convert that to an integer.

Is that possible without just using a number of select case statements?

I would like to do this in .NET 3.5

A: 

You could store Name->Number mappings in an array (look through the array until you find the one you want) or a hash (lookup the month name in the hash to get a number -- benefits from supporting any number of languages and abbreviations, too). I'd rather store the information in data structures than in code, but that might just be my own irrational behavior.

EDIT

In response to @roboshop's "Sounds like a lot of work", perhaps it is compared to one-liners that the platform supports, but if your customers ask you to support abbreviations such as "Jan", "Fe", "Mar", I think using a data structure gives a lot of additional flexibility:

months = { "ja" => 1, "jan" => 1, "january" => 1,
           "fe" => 2, "feb" => 2, "february" => 2,
           "ma" => 3, "mar" => 3, "march" => 3,
           "ap" => 4, "apr" => 4, "april" => 4,
           "my" => 5, "may" => 5,
           "jn" => 6, "jun" => 6, "june" => 6,
           "jl" => 7, "jul" => 7, "july" => 7,
           "au" => 8, "aug" => 8, "august" => 8,
           "se" => 9, "sep" => 9, "sept" => 9, "september" => 9,
           "oc" => 10, "oct" => 10, "october" => 10,
           "no" => 11, "nov" => 11, "november" => 11,
           "de" => 12, "dec" => 12, "december" => 12,
           "januar" => 1,
           "februar" => 2,
           "märz" => 3,
           "mai" => 5,
           "juni" => 6,
           "oktober" => 10,
           "dezember" => 12}

puts "Month %s is %d" % [ARGV[0], months[ARGV[0].downcase]]

Of course, now you have to know the localized versions of months your users want, but it is far easier to support requested abbreviations.

sarnold
sounds like a lot of work
RoboShop
A: 

In SQL Server do this SELECT DATEPART(month, GETDATE())

Also a duplicate of this question http://stackoverflow.com/questions/258793/how-to-parse-a-month-name-string-to-an-integer-for-comparison-in-c

Ryk
+1  A: 

You can use DateTime.Parse and then get the Month property of the date:

string monthName = "January";
DateTime.Parse(String.Format("{0} 1, 2000", monthName)).Month
Tahbaza