0

This is a quite common situation and usually we have 2 approaches: 1 create an array of string with the first element empty so we can replace directly

String[] months = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; //first empty so we can replace directly

for(int i =1;i <=12;i++)
        {
            //Do the magic
            xval.Add(months[i] );
        }

or we could create the same array without the empty element and replace the index minus one (which seems less readable to me)

Since it is a quite common use case, are there any better options (more readable maybe) to replace the month number to month name? (i.e. 1/12/1983 to 1/Dec/1983 and so on)

Sim1
  • 534
  • 4
  • 24
  • 1
    Side Note: Try to include the language you're working in as one of your tags. – Tim Lewis Mar 17 '15 at 17:12
  • done, thank you for pointing that out, even if I'm looking for a general best practice (like a design pattern if the term is correct) – Sim1 Mar 17 '15 at 17:14
  • 1
    No problem, I figured it was C#. And even if it's general, you'll also notice your post now has proper syntax highlighting, so it's always best to include it :) – Tim Lewis Mar 17 '15 at 17:15
  • 1
    Also see: http://stackoverflow.com/questions/3184121/get-month-name-from-month-number – NightOwl888 Mar 17 '15 at 17:17
  • you guys are awesome! Thank you very much for this elegant solution! – Sim1 Mar 17 '15 at 17:19

1 Answers1

3

DateTimeFormatInfo class will be helpful.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;

namespace ConsoleApplication6
{
   class Program
   {
       static void Main(string[] args)
       {
           DateTimeFormatInfo dateTimeInfo = new DateTimeFormatInfo();
           Console.Write(dateTimeInfo.GetAbbreviatedMonthName(4)); // Display April
           Console.ReadKey();
       }
   }
}
Júlio Murta
  • 555
  • 2
  • 15