解析日期时间到月份名称

时间:2013-01-18 08:25:27

标签: c# asp.net datetime tryparse

您好我试图将我在MSSQL中的int日期时间转换为月份名称。我来自丹麦(DK),代码是。

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

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

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

由于

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

4 个答案:

答案 0 :(得分:0)

您可以使用自己的月份枚举

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

然后

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

您不需要再次转换为DateTime,TryParse会为您提供日期时间

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

//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));

答案 3 :(得分:0)

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