【问题标题】:c# is there a easy way to convert month integer to namec#有没有一种简单的方法将月份整数转换为名称
【发布时间】:2012-07-03 21:40:19
【问题描述】:

我正在尝试为博客应用程序创建存档列表。我有一个 veiw 模型,它有这个代码 sn-p:

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

我正在尝试将 item.ArchiveMonth 打印为“Jan”而不是“1”。

ArchiveListModel 如下:

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

从存储库中读取博客如下:

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

非常感谢。

【问题讨论】:

标签: c# asp.net-mvc-3 monthcalendar


【解决方案1】:
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);

或缩写

CultureInfo.CurrentUICulture.DateTimeFormat.AbbreviatedMonthNames[1];

【讨论】:

  • 我认为这不会返回缩写名称,但很高兴知道。
  • 取缩写名称使用3个符号
  • 由于某种原因,CultureInfo 以前无法正常工作。我在stackoverflow上研究过。无论如何它现在可以工作了!
【解决方案2】:

获取完整的月份名称

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

或者你可以使用日期时间字符串格式:

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

或者您可以对缩写列表进行查找

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

【讨论】:

  • 我必须使用 [month-1] 作为第三个选项来给我正确的缩写月份。
【解决方案3】:

我相信你想要:

.ToString("MMM");

您甚至可以为特定月份创建自己的 DateTime 对象:

DateTime jan = new DateTime(2012, 1, 1);
return jan.Date.ToString("MMM");

【讨论】:

    【解决方案4】:

    如果您想对数据库中的数据使用 ViewBags,您也可以轻松地使用该格式。请记住。

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

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 2010-09-06
      • 2016-06-13
      • 1970-01-01
      • 2022-09-24
      相关资源
      最近更新 更多