3

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
WP_Insane
  • 117
  • 1
  • 1
  • 8
  • 2
    Loop over the months? – Christian Sauer Aug 21 '14 at 06:59
  • 1
    "This two codes works only to get the current month. I need to get the short month name for all the months." - so some sort of looping construct would seem appropriate... – Mitch Wheat Aug 21 '14 at 06:59
  • and fill an hashmap like structure (Dictionary IIRC) – BigMike Aug 21 '14 at 06:59
  • 1
    Its probably much easier to just create a dictionary or class, that has both parts and will return your desired result, it will only have 12 entries so shouldn't be too laborious – Sayse Aug 21 '14 at 07:00
  • `If I give "agosto", it should return "ago.". How could I achieve this?` I think the OP wants a function to parse the month's full name into the abbreviation. – disappointed in SO leadership Aug 21 '14 at 07:05
  • What is the real problem ? You know how to get the abbreviated month name of a given datetime?! So the only problem is that you don't know how to get the other months. But _what_ months do you need at all? – Tim Schmelter Aug 21 '14 at 07:09

11 Answers11

11

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;
}
Community
  • 1
  • 1
Rawling
  • 49,248
  • 7
  • 89
  • 127
4

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)
aduexjr
  • 81
  • 2
3

Try this way

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

foreach (string name in dateTimeInfo.AbbreviatedMonthNames)
{
    Console.WriteLine(name);
}
Kamlesh Arya
  • 4,864
  • 3
  • 21
  • 28
  • 6
    Sorry but I don't understand why this answer upvoted so much. Yes, it gets all abbreviated month names but OP doesn't want this. He/she wants to get abbreviated month name from full month name of his `CurrentCulture`. I don't understand why you used `en-US` culture either. – Soner Gönül Aug 21 '14 at 07:22
  • Sorry, if your answer dint get any upvotes.:P .. Actually my answer was just an example. I used US english as a culture. OP can try same approach for CurrentCulture. – Kamlesh Arya Aug 21 '14 at 07:27
  • 5
    Getting upvote is not the point. The point is; try to giving the right answer. This one doesn't even answer the question at all. – Soner Gönül Aug 21 '14 at 07:32
3

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");

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • I don't understand reason of `foreach` and comparison, when you have the full name in parameter. Just use it ... – Xaruth Aug 21 '14 at 11:32
  • @Xaruth I think this is more understandable for OP to how to get these values. If you look for a cleaner/better solution, check [Rawling's answer](http://stackoverflow.com/a/25424933/447156) as well. – Soner Gönül Aug 21 '14 at 11:34
2

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

Community
  • 1
  • 1
1

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"));
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Lee
  • 586
  • 3
  • 5
  • 1
    This has the drawback, that the result changes it's order depending of the current month. Create a variable which is set to january like this: var test = new DateTime(2014,1,1) – Christian Sauer Aug 21 '14 at 07:02
  • Hi Christian, agreed but it depends on the user's use case. If s/he needs to populate a dropdown list to select a month then such an approach would work well. i.e. showing the current month as the first option. – Lee Aug 21 '14 at 07:04
  • 2
    So, this gets all abbreviated names starts from now. Then what? What is the point? Doesn't answer to question at all. – Soner Gönül Aug 21 '14 at 07:24
0

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))];
David Clarke
  • 12,888
  • 9
  • 86
  • 116
0

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;
    }
}

}

Markus Deibel
  • 1,261
  • 20
  • 26
0

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

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

vikas
  • 11
  • This seems wrong? It will return _current date_ in a format containing days, month and years, and not the short month for _all months_ – Ward Dec 29 '17 at 07:39
0

This is what you need:

var dateUtil = DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture);
return dateUtil.AbbreviatedMonthNames[DateTime.Now.Month -1];
Emmanuel
  • 1
  • 1
  • 1
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – β.εηοιτ.βε May 31 '20 at 14:12
-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 />");
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Kyaw Wanna
  • 11
  • 2
  • Sorry for showing only the code. What I understand is you want to get from long month name to short in every month of the year. So, I gave an example about adding one constant date in "Dat" variable. And then, make "for loop". Please check the code, that I edited. – Kyaw Wanna Aug 21 '14 at 07:47