简体   繁体   中英

How to get short month name from full month name?

I need to get the short month name for the full month name.

For example,

DateTime.Now.ToString("MMMM", CultureInfo.CurrentCulture);
this returns - "agosto"

DateTime.Now.ToString("MMM", CultureInfo.CurrentCulture);
this returns - "ago."

This two codes works only to get the current month. I need to get the short month name for all the months.

If I give "agosto" , it should return "ago." . How could I achieve this?

An alternative to Soner 's answer that doesn't use a loop:

public static string GetAbbreviatedFromFullName(string fullname)
{
    DateTime month;
    return DateTime.TryParseExact(
            fullname,
            "MMMM",
            CultureInfo.CurrentCulture,
            DateTimeStyles.None,
            out month)
        ? month.ToString("MMM")
        : null;
}

Try this way

var culture = CultureInfo.GetCultureInfo("en-US");
var dateTimeInfo = DateTimeFormatInfo.GetInstance(culture);

foreach (string name in dateTimeInfo.AbbreviatedMonthNames)
{
    Console.WriteLine(name);
}

If I give "agosto", it should return "ago."

Then you can use DateTimeFormatInfo.MonthNames like;

public static string GetAbbreviatedFromFullName(string fullname)
{
    string[] names = DateTimeFormatInfo.CurrentInfo.MonthNames;
    foreach (var item in names)
    {
        if (item == fullname)
        {
            return DateTime.ParseExact(item, "MMMM", CultureInfo.CurrentCulture)
                                 .ToString("MMM");
        }
    }
    return string.Empty;
}

And then can call it like GetAbbreviatedFromFullName("agosto") ;

If I understand your question correctly, you want to pass a function the Month's full name, and get the month's short name?

This method assumes the MonthLongName passed is a valid month name in the current culture. If it is not, it will throw an exception. If that will ever be a possibility, do some validation.

public String GetMonthShortName(String MonthLongName)
{
    return DateTime.ParseExact(MonthLongName, "MMMM", CultureInfo.CurrentCulture ).ToString("MMM", CultureInfo.CurrentCulture);
}

Some code borrowed from this answer

If you can get the month number, this way is pretty easy to get the abbreviated name or full name.

Abbreviated Month Name:

 CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(DateTime.Today.Month)

Full Month Name:

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Today.Month)

If you want all month names you could use something as follows:

for (int i = 0; i < 12; i++)
{
    Console.WriteLine(DateTime.Now.AddMonths(i).ToString("MMM"));
}

CultureInfo already has arrays representing both full and abbreviated month names:

CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames[
    Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                     t => t.Equals("agosto", StringComparison.CurrentCultureIgnoreCase))];

I ran into the same problem and I would like to add my solution (based on @Rawling's answer)for completeness.

Since I needed the conversion in XAML I wrote the following converter.

As I didn't want to add months and days to the resources, the conversion goes from Invariant long (which I have in the "Tag" of the XAML element) to the short Current culture (needed in the "Content") and thus saves extra translations

I also created a converter for the weekdays along the same lines.

using System;
using System.Globalization;
using System.Windows.Data;

namespace Rittal.RiZone.GUI.ValueConverters
{
    public class LongToShortMonthConverter : IValueConverter
    {
    /// <summary>
    /// 
    /// </summary>
    /// <param name="value">Long month name from InvariantCulture</param>
    /// <param name="targetType"></param>
    /// <param name="parameter"></param>
    /// <param name="culture"></param>
    /// <returns>Short text representation of the month in CurrentCulture; null in case no match was found</returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null) return null;

        DateTime month;
        return DateTime.TryParseExact(
            value.ToString(),
            "MMMM",
            CultureInfo.InvariantCulture,
            DateTimeStyles.None,
            out month)
            ? month.ToString("MMM", CultureInfo.CurrentCulture)
            : null;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="value">Short month name from CurrentCulture</param>
    /// <param name="targetType"></param>
    /// <param name="parameter"></param>
    /// <param name="culture"></param>
    /// <returns>Long text representation of the month in InvariantCulture; null in case no match was found</returns>
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null) return null;

        DateTime month;
        return DateTime.TryParseExact(
            value.ToString(),
            "MMM",
            CultureInfo.CurrentCulture,
            DateTimeStyles.None,
            out month)
            ? month.ToString("MMMM", CultureInfo.InvariantCulture)
            : null;
    }
}

}

DateTime.Now.ToString("dd MMM yyyy"); this returns - "agosto";

DateTime.Now.ToString("dd MMM yyyy"); this returns - "ago.";

This is what you need:

var dateUtil = DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture);
return dateUtil.AbbreviatedMonthNames[DateTime.Now.Month -1];
CultureInfo ci = CultureInfo.CreateSpecificCulture("en-US");
DateTimeFormatInfo abrv = ci.DateTimeFormat;

DateTime dat = new DateTime(2014, 1, 1);

for (int ctr = 0; ctr < abrv.Calendar.GetMonthsInYear(dat.Year); ctr++) {
     Response.Write(dat.AddMonths(ctr).ToString("MMM", abrv) + "<br />");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM