2

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.

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
Tripping
  • 919
  • 4
  • 18
  • 36
  • possible duplicate of [Is there a predefined enumeration for Month in the .NET library?](http://stackoverflow.com/questions/899565/is-there-a-predefined-enumeration-for-month-in-the-net-library) – DaveShaw Jul 03 '12 at 21:42
  • Not a duplicate question, but I think the answer will help. – DaveShaw Jul 03 '12 at 21:43

4 Answers4

11
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);

or for abrev

CultureInfo.CurrentUICulture.DateTimeFormat.AbbreviatedMonthNames[1];
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
4

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];
BlackSpy
  • 5,563
  • 5
  • 29
  • 38
3

I believe you want:

.ToString("MMM");

You can even create your own DateTime object for a specific month:

DateTime jan = new DateTime(2012, 1, 1);
return jan.Date.ToString("MMM");
Chris Gessler
  • 22,727
  • 7
  • 57
  • 83
0

If you want to use ViewBags for the datas from your database you can also use that format easly. Just keep in mind.

@foreach (var item in ViewBag.HealthCare)
{
    @item.Created_Date.ToString("MMMM yyyy")

}
lukess
  • 964
  • 1
  • 14
  • 19
Emre
  • 83
  • 2
  • 10