Вопрос

Hi im trying to convert my int datetime in MSSQL to monthname instead. Im from denmark(DK) and the code is.

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

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

but i think im missing something.

Thanks

EDIT: I cant get it to work. I'm getting all the dates from a database, and I want to use the monthnames in a search function. I'm not sure if I have to do something else when its a search function.

Это было полезно?

Решение

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

Другие советы

You can your own Month Enum

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

then

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

You don't need to convert to DateTime again, TryParse will give you the datetime

try this :

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top