【问题标题】:parse datetime to monthname将日期时间解析为月份名称
【发布时间】:2013-01-18 08:25:27
【问题描述】:

您好,我正在尝试将我在 MSSQL 中的 int datetime 转换为 monthname。我来自丹麦(DK),代码是。

    DateTime dateTime;
    if (DateTime.TryParse(KeyWord, out dateTime))
    {
        KeyWord = Convert.ToDateTime(KeyWord).ToLongDateString();
    }

    objCMD.Parameters.AddWithValue("@keyword", "%" + KeyWord + "%");

但我认为我错过了一些东西。

谢谢

编辑:我无法让它工作。我正在从数据库中获取所有日期,并且我想在搜索功能中使用月份名称。我不确定当它是搜索功能时我是否需要做其他事情。

【问题讨论】:

  • 你要转换的数据格式是什么?
  • 另外,如果你已经做过 TryParse,你可以直接做 KeyWord = dateTime.ToLongDateString();

标签: c# asp.net datetime tryparse


【解决方案1】:
//Create localization object from http://stackoverflow.com/questions/3184121/get-month-name-from-month-number
System.Globalization.DateTimeFormatInfo dtfi = new System.Globalization.DateTimeFormatInfo();
//Initialize dateTime
DateTime.TryParse(KeyWord, out dateTime);
//Write Month name in KeyWord
KeyWord = string.Format("%{0}%", dtfi.GetMonthName(dateTime.Month));

【讨论】:

    【解决方案2】:

    您可以自己的月份枚举

    enum Month
    {
       January = 1,
       February = 2,
       ...
       ...
       Decmeber =12
    }
    

    然后

        DateTime dateTime;
        if (DateTime.TryParse(KeyWord, out dateTime))
        {
            KeyWord = ((Month)dateTime.Month).ToString();
        }
    

    你不需要再转换成 DateTime,TryParse 会给你日期时间

    【讨论】:

    • 谢谢老兄。但是确实有效:(它是我希望能够搜索的搜索功能,可以搜索月份名称而不是月份编号。
    • 与其说“但没用”,请尽量让你的问题更清晰和有例子!!!
    【解决方案3】:

    试试这个:

            DateTime dateTime;
            String KeyWord = "11/12/13"; // MM/dd/yy
            if (DateTime.TryParse(KeyWord, out dateTime))
            {
                KeyWord = Convert.ToDateTime(KeyWord).ToString("MMMM"); // Full month name
                KeyWord = Convert.ToDateTime(KeyWord).ToString("MMM"); // The abbreviated name of the month. 
            }
    

    【讨论】:

    • 谢谢老兄。但是确实有效:(它是我希望能够搜索的搜索功能,可以搜索月份名称而不是月份编号。
    • 你能给出示例输入和输出吗?
    【解决方案4】:
    string yourMonth= Date = DateTime.Now.Month.ToString();   
    string selectedYear= DateTime.Now.Year.ToString();
    ViewBag.Today = 
    System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName
    (Int32.Parse(yourMonth)) + selectedYear;
    

    works fine for me hopefully it will help others

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      相关资源
      最近更新 更多