Tripping Tripping - 23 days ago 7
C# Question

c# is there a easy way to convert month integer to name

I am trying to create a archive list for a blog application. I have a veiw model which has this code snippet:

@model IEnumerable<NPLHBlog.Models.ArchiveListModels>
...
@foreach (var item in Model)
{
<li>@item.ArchiveMonth/@item.ArchiveYear : @item.PostCount</li>
}
...


I am trying to print the item.ArchiveMonth as 'Jan' instead of '1'.

the ArchiveListModel is as follows:

public class ArchiveListModels
{
public int ArchiveYear { get; set; }
public int ArchiveMonth { get; set; }
public int PostCount { get; set; }
}


and blogs are read from repository as follows:

public IQueryable<ArchiveListModels> ArchiveList()
{
var archiveList = from blogs in db.Blogs
group blogs by new { blogs.PublishDate.Year, blogs.PublishDate.Month }
into dateGroup
select new ArchiveListModels()
{
ArchiveYear = dateGroup.Key.Year,
ArchiveMonth = dateGroup.Key.Month,
PostCount = dateGroup.Count()
};
return archiveList;
}


Many thanks.

Answer Source

To get the full month name

int month = 1;
System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(month);

Or you can use the datetime string format:

int month = 1;
var dt = new DateTime(2012, month, 1):
var monthAbbr = dt.ToString("MMM");

Or you can do a lookup against the abbreviations list

int month = 1;
var monthAbbr =     System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.AbbreviatedMonthNames[month];