Reputation: 929
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.
Upvotes: 2
Views: 7007
Reputation: 83
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")
}
Upvotes: 0
Reputation: 13460
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
or for abrev
CultureInfo.CurrentUICulture.DateTimeFormat.AbbreviatedMonthNames[1];
Upvotes: 11
Reputation: 23123
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");
Upvotes: 3
Reputation: 5603
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];
Upvotes: 4