Click here to Skip to main content
15,880,725 members
Articles / Programming Languages / C#
Tip/Trick

Get Month Name from Month Number or vice versa

Rate me:
Please Sign up or sign in to vote.
4.14/5 (7 votes)
13 Jun 2012CPOL 148.9K   4   6
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 ..

C#
int iMonthNo = 3; 
DateTime dtDate = new DateTime(2000, iMonthNo, 1); 
string sMonthName = dtDate.ToString("MMM"); 
string sMonthFullName = dtDate.ToString("MMMM"); 

And as well as if we have full name or half name of month and want to get month number, then we can use the code below ..

C#
string sMonthName = "Jan"; 
sMonthName = "January"; 
int iMonthNo = Convert.ToDateTime("01-" + sMonthName + "-2011").Month; 

This is an optimized process for that in place of conditional statements..

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Super Eminent Softwares
India India
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

- .NET Framework 2.0
- C#
- ASP.NET
- ASP.NET AJAX
- SQL Server 2005
- ADO .NET
- XML Webservices
- Payment systems

Feel free to take a look at the website and see Microsoft's new technologies in action
This is a Organisation

43 members

Comments and Discussions

 
SuggestionThis is not "optimal" but it is fast, and can throw an exception. Pin
Matt T Heffron13-Jun-12 12:36
professionalMatt T Heffron13-Jun-12 12:36 
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.1047346
Original: Convert.ToDateTime = 0.4926248
New: initializing new MonthsHelper() = 0.3544563
New: MonthsHelper.FullMonthName = 0.0615322
New: MonthsHelper.FullMonthNameToNumber = 0.0207368
Given 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.

MonthsHelper.cs:
C#
namespace Months
{
  using System;
  using System.Collections.Generic;
  using System.Globalization;

  /// <summary>
  /// Class to help with month name/number conversion
  /// </summary>
  public class MonthsHelper
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="MonthsHelper"/> class.
    /// </summary>
    public MonthsHelper()
      : this(CultureInfo.CurrentCulture)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="MonthsHelper"/> class.
    /// </summary>
    /// <param name="culture">The culture.</param>
    public MonthsHelper(CultureInfo culture)
      : this((culture ?? CultureInfo.CurrentCulture).DateTimeFormat)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="MonthsHelper"/> class.
    /// </summary>
    /// <param name="dateFormatInfo">The date format info.</param>
    public MonthsHelper(DateTimeFormatInfo dateFormatInfo)
    {
      DateFormatInfo = dateFormatInfo ?? CultureInfo.CurrentCulture.DateTimeFormat;
      for (int m = 0; m < MonthArrayCount; m++)
      {
        var name = DateFormatInfo.MonthNames[m];
        FullMonthNameToNumberMap[name] = m + 1;
        name = DateFormatInfo.AbbreviatedMonthNames[m];
        ShortMonthNameToNumberMap[name] = m + 1;
        name = DateFormatInfo.MonthGenitiveNames[m];
        FullMonthGenitiveNameToNumberMap[name] = m + 1;
        name = DateFormatInfo.AbbreviatedMonthGenitiveNames[m];
        ShortMonthGenitiveNameToNumberMap[name] = m + 1;
      }
    }

    private const int MonthArrayCount = 13;    // The 4 Month Names arrays are always 13 long. (per MSDN)
    private readonly DateTimeFormatInfo DateFormatInfo;
    private readonly Dictionary<string, int> FullMonthNameToNumberMap = new Dictionary<string, int>(MonthArrayCount, StringComparer.Ordinal);
    private readonly Dictionary<string, int> ShortMonthNameToNumberMap = new Dictionary<string, int>(MonthArrayCount, StringComparer.Ordinal);
    private readonly Dictionary<string, int> FullMonthGenitiveNameToNumberMap = new Dictionary<string, int>(MonthArrayCount, StringComparer.Ordinal);
    private readonly Dictionary<string, int> ShortMonthGenitiveNameToNumberMap = new Dictionary<string, int>(MonthArrayCount, StringComparer.Ordinal);

    /// <summary>
    /// Gets the full name of the month.
    /// </summary>
    /// <param name="monthNumber">The month number.</param>
    /// <returns>Full name of the month, or string.Empty if invalid monthNumber</returns>
    public string FullMonthName(int monthNumber)
    {
      if (monthNumber < 1 || monthNumber > 12)
        return string.Empty;
      return DateFormatInfo.MonthNames[monthNumber - 1];
    }

    /// <summary>
    /// Gets the short name of the month.
    /// </summary>
    /// <param name="monthNumber">The month number.</param>
    /// <returns>Short name of the month, or string.Empty if invalid monthNumber</returns>
    public string ShortMonthName(int monthNumber)
    {
      if (monthNumber < 1 || monthNumber > 12)
        return string.Empty;
      return DateFormatInfo.AbbreviatedMonthNames[monthNumber - 1];
    }

    /// <summary>
    /// Gets the full genitive name of the month.
    /// </summary>
    /// <param name="monthNumber">The month number.</param>
    /// <returns>Full genitive name of the month, or string.Empty if invalid monthNumber</returns>
    public string FullMonthGenitiveName(int monthNumber)
    {
      if (monthNumber < 1 || monthNumber > 12)
        return string.Empty;
      return DateFormatInfo.MonthGenitiveNames[monthNumber - 1];
    }

    /// <summary>
    /// Gets the short genitive name of the month.
    /// </summary>
    /// <param name="monthNumber">The month number.</param>
    /// <returns>Short genitive name of the month, or string.Empty if invalid monthNumber</returns>
    public string ShortMonthGenitiveName(int monthNumber)
    {
      if (monthNumber < 1 || monthNumber > 12)
        return string.Empty;
      return DateFormatInfo.AbbreviatedMonthGenitiveNames[monthNumber - 1];
    }

    /// <summary>
    /// Gets the month number (1-based) for the month name.
    /// </summary>
    /// <param name="monthName">Name of the month.</param>
    /// <remarks>Uses all 4 possible sets of month names to attempt to determine month number.</remarks>
    /// <returns>The month number (1-12) for the month name, or -1 if monthName is invalid.</returns>
    public int MonthNameToNumber(string monthName)
    {
      int monthNumber;
      if (!FullMonthNameToNumberMap.TryGetValue(monthName, out monthNumber) &&
          !ShortMonthNameToNumberMap.TryGetValue(monthName, out monthNumber) &&
          !FullMonthGenitiveNameToNumberMap.TryGetValue(monthName, out monthNumber) &&
          !ShortMonthGenitiveNameToNumberMap.TryGetValue(monthName, out monthNumber))
      {
        monthNumber = -1;
      }
      return monthNumber;
    }

    /// <summary>
    /// Gets the month number (1-based) for the month name.
    /// </summary>
    /// <param name="monthName">Full name of the month.</param>
    /// <returns>The month number (1-12) for the month name, or -1 if monthName is invalid.</returns>
    public int FullMonthNameToNumber(string monthName)
    {
      int monthNumber;
      if (!FullMonthNameToNumberMap.TryGetValue(monthName, out monthNumber))
      {
        monthNumber = -1;
      }
      return monthNumber;
    }

    /// <summary>
    /// Gets the month number (1-based) for the month name.
    /// </summary>
    /// <param name="monthName">Short name of the month.</param>
    /// <returns>The month number (1-12) for the month name, or -1 if monthName is invalid.</returns>
    public int ShortMonthNameToNumber(string monthName)
    {
      int monthNumber;
      if (!ShortMonthNameToNumberMap.TryGetValue(monthName, out monthNumber))
      {
        monthNumber = -1;
      }
      return monthNumber;
    }

    /// <summary>
    /// Gets the month number (1-based) for the month name.
    /// </summary>
    /// <param name="monthName">Full genitive name of the month.</param>
    /// <returns>The month number (1-12) for the month name, or -1 if monthName is invalid.</returns>
    public int FullMonthGenitiveNameToNumber(string monthName)
    {
      int monthNumber;
      if (!FullMonthGenitiveNameToNumberMap.TryGetValue(monthName, out monthNumber))
      {
        monthNumber = -1;
      }
      return monthNumber;
    }

    /// <summary>
    /// Gets the month number (1-based) for the month name.
    /// </summary>
    /// <param name="monthName">Short genitive name of the month.</param>
    /// <returns>The month number (1-12) for the month name, or -1 if monthName is invalid.</returns>
    public int ShortMonthGenitiveNameToNumber(string monthName)
    {
      int monthNumber;
      if (!ShortMonthGenitiveNameToNumberMap.TryGetValue(monthName, out monthNumber))
      {
        monthNumber = -1;
      }
      return monthNumber;
    }
  }
}


Usage and timing in Program.cs:
C#
using System;
using System.Diagnostics;

namespace Months
{
  class Program
  {
    static readonly string[] FullMonths = { "null", "January", "February", "March", "April", "May", "June", 
                                            "July", "August", "September", "October", "November", "December" };
    //static readonly string[] ShortMonths = { "null", "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
    //                                         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    static void Main(string[] args)
    {
      Stopwatch sw = new Stopwatch();
      sw.Start();
      const int repeat = 100000;
      for (int r = 0; r < repeat; r++)
      {
        for (int m = 1; m <= 12; m++)
        {
          DateTime dtDate = new DateTime(2000, m, 1);
          //var sMonthName = dtDate.ToString("MMM");
          var sMonthFullName = dtDate.ToString("MMMM");
        }
      }
      sw.Stop();
      Console.WriteLine("Original: DateTime.ToString = {0}", TimeSpan.FromTicks(sw.ElapsedTicks));
      sw.Restart();
      for (int r = 0; r < repeat; r++)
      {
        for (int m = 1; m <= 12; m++)
        {
          DateTime dtDate = new DateTime(2000, m, 1);
          //var sMonthName = ShortMonths[m];
          //var iMonthNo = Convert.ToDateTime("01-" + sMonthName + "-2011").Month;
          var sMonthName = FullMonths[m];
          var iMonthNo = Convert.ToDateTime("01-" + sMonthName + "-2011").Month;
        }
      }
      sw.Stop();
      Console.WriteLine("Original: Convert.ToDateTime = {0}", TimeSpan.FromTicks(sw.ElapsedTicks));
      MonthsHelper helper = new MonthsHelper();
      sw.Restart();
      for (int r = 0; r < repeat; r++)
      {
        helper = new MonthsHelper();
      }
      sw.Stop();
      Console.WriteLine("New: initializing new MonthsHelper() = {0}", TimeSpan.FromTicks(sw.ElapsedTicks));
      sw.Restart();
      for (int r = 0; r < repeat; r++)
      {
        for (int m = 1; m <= 12; m++)
        {
          //var sMonthName = helper.ShortMonthName(m);
          var sMonthFullName = helper.FullMonthName(m);
        }
      }
      sw.Stop();
      Console.WriteLine("New: MonthsHelper.FullMonthName = {0}", TimeSpan.FromTicks(sw.ElapsedTicks));
      sw.Restart();
      for (int r = 0; r < repeat; r++)
      {
        for (int m = 1; m <= 12; m++)
        {
          //var sMonthName = ShortMonths[m];
          //var iMonthNo = helper.ShortMonthNameToNumber(sMonthName);
          var sMonthName = FullMonths[m];
          var iMonthNo = helper.FullMonthNameToNumber(sMonthName);
        }
      }
      sw.Stop();
      Console.WriteLine("New: MonthsHelper.FullMonthNameToNumber = {0}", TimeSpan.FromTicks(sw.ElapsedTicks));
      Console.ReadLine();
    }
  }
}

GeneralRe: This is not "optimal" but it is fast, and can throw an exception. Pin
MacSpudster13-Jun-12 12:59
professionalMacSpudster13-Jun-12 12:59 
GeneralRe: This is not "optimal" but it is fast, and can throw an exception. Pin
Matt T Heffron13-Jun-12 13:11
professionalMatt T Heffron13-Jun-12 13:11 
GeneralRe: This is not "optimal" but it is fast, and can throw an exception. Pin
Technoses13-Jun-12 19:12
Technoses13-Jun-12 19:12 
GeneralRe: This is not "optimal" but it is fast, and can throw an exception. Pin
cansino5-Jul-12 21:31
cansino5-Jul-12 21:31 
QuestionExtension Methods Pin
Matt U.13-Jun-12 6:53
Matt U.13-Jun-12 6:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.