【问题标题】:C# - Formatting DateTime to Month [duplicate]C# - 将日期时间格式化为月份 [重复]
【发布时间】:2014-06-24 18:18:47
【问题描述】:

我正在从下拉列表中作为完整日期和时间的数据库中检索 DateTime。我需要的只是该下拉列表中该日期时间的月份,以 word 格式显示。

如下:

[System.Web.Services.WebMethod]
public static string OnChainChange(string ChainId)
{
    DataTable table = DBHelper.GetMonthList(ChainId.Trim());

    string result = string.Empty;

    foreach (DataRow dr in table.Rows)
    {
        DateTime thisDate = Convert.ToDateTime(dr["FromDate"].ToString());

        result += new ListItem(thisDate.ToString("MMMM"), thisDate.Month.ToString("MMMM"));
        //result += dr["FromDate"].ToString() + ";";
    }

    return result;
}

LB - 这个问题是不同的。我正在尝试将其作为新的 listItem 来执行。我了解如何转换 DateTime int。我希望你能找到一个重复的答案! :)

【问题讨论】:

  • 问题出在哪里?
  • @L.B,问题不是获取月份名称,而是thisDate.Month.ToString("MMMM"),尝试使用DateTime 格式转换int

标签: c# asp.net web-services datetime drop-down-menu


【解决方案1】:

问题是

thisDate.Month.ToString("MMMM")

DateTime.Month 的类型为 int,如果您尝试将其添加为值,则只需使用

thisDate.Month.ToString() //without passing in any parameter

如果您希望值是月份名称,请使用:

thisDate.ToString("MMMM")

不是将参数传递给ToString,而是将所有值设置为MMMM

【讨论】:

  • 似乎不起作用:(你的评论很有道理!
  • @ebutlerdeveloper,使用thisDate.Month.ToString(),您究竟需要什么作为ListItem、月份编号或月份名称中的值?
  • 我需要月份名称
  • @ebutlerdeveloper,然后使用thisDate.ToString("MMMM")
猜你喜欢
  • 2021-07-04
  • 2014-11-25
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 2020-04-01
  • 1970-01-01
相关资源
最近更新 更多