c# get month from string code example

Example 1: c# get month number from name

int month = DateTime.ParseExact(MonthNameStr, "MMMM", CultureInfo.CurrentCulture ).Month

Example 2: getname of month from date c#

using System;
using System.Globalization;

class Program
{
    static void Main()
    {

        Console.WriteLine(DateTime.Now.ToMonthName());
        Console.WriteLine(DateTime.Now.ToShortMonthName());
        Console.Read();
    }
}

static class DateTimeExtensions
{
    public static string ToMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
    }

    public static string ToShortMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
    }
}

Example 3: find month number from date C#

string name = DateTime.ParseExact("01/21/2014", "MM/dd/yyyy", null).ToString("MMMM"); //January