Rathpanha Sarun Rathpanha Sarun - 1 year ago 116
C# Question

How to convert digit month to the full name of month in C# console

I want to convert digit month that is inputed by User to the name of month. I find it easily to use if else condition, but is there any function I can use without using condition? It's take me to write alot of code.
Note : Just month!

int month = 0;
bool TempResult = false;
Console.Write("Month: ");
TempResult = int.TryParse(Console.ReadLine(), out Month);

Answer Source

There are two reasonably simple options:

  • Construct a date using that number as the month, and then format it with a custom format, e.g.

    DateTime date = new DateTime(2000, month, 1);
    string monthName = date.ToString("MMMM");
  • Use DateTimeFormatInfo.MonthNames

    DateTimeFormatInfo info = CultureInfo.CurrentCulture.DateTimeFormat; 
    // The array is 0-based, e.g. MonthNames[0] is for January
    string monthName = info.MonthNames[month - 1];

Both of these will take the name from the current culture; in either case you can specify a different CultureInfo if you want. (In the first case, use it as a second argument to ToString.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download