Get Month Name from Month Number or vice versa

We need a query to display month name and we have month number for that. Then firstly we create a switch case statement of if else statement for that. But we can get that easily by using the below code ..

Share

About the Author

My name is Peeyush Shah and I am working with Microsoft.Net Framework at Jaipur, India with a Taxaction Software Development Company Named Professional Softec Pvt. Ltd.

My main focus is the development of online application. We also develop custom software solutions for our customers and are able to support developers in using the following technologies, because we use them every day

Comments and Discussions

The code presented is pretty fast, but it isn't "optimal", and it can throw exceptions if the month number is invalid when getting the month name, and likewise if the month name is invalid when getting the month number.

Using the info in the DateTimeFormatInfo class, from the CultureInfo's DateTimeFormat property, the month names are already available. Get them directly without the overhead of the .ToString() and Convert.ToDateTime()

The code below is faster (100,000 iterations, in seconds)Original: DateTime.ToString = 0.1047346Original: Convert.ToDateTime = 0.4926248New: initializing new MonthsHelper() = 0.3544563New: MonthsHelper.FullMonthName = 0.0615322New: MonthsHelper.FullMonthNameToNumber = 0.0207368Given these times are for 100K iterations, the differences are not really significant, but this may show some ideas for similar problems where the computation is expensive.

Yes, overall complexity, but the complexity of MonthsHelper is all hidden away, and at the usage point, the code will appear simpler.(And if you don't need the support for the Genitive names, half of it goes away.)