How do I format a DateTime variable to get the month and then put the value into a string in C #? [VS2005]

DateTime dt = Convert.ToDateTime(dateTimePicker1.Text); //taken the DateTime from form
string dt1 = String.Format("Y", dt); //trying to make so that it comes to "August 2009"

      

Tried it but all I get is dt1 = "Y".

+2


source to share


6 answers


DateTime dt = Convert.ToDateTime(dateTimePicker1.Text); //taken the DateTime from form
string dt1 = dt.ToString("MMMM yyyy")

      



+5


source


DateTime dt = Convert.ToDateTime(dateTimePicker1.Text); //taken the DateTime from form
string dt1 = String.Format("{0:MMMM yyyy}", dt); //trying to make so that it comes to "August 2009"

      



+3


source


You have other answers that use ToString

.. If you want to use string.Format

, try this:

string dt1 = string.Format("{0:Y}", dt);

      

+2


source


Other answers will work. I just wanted to comment on the reason why your code is not working. String.Format

is designed to format more than 1 variable at a time. You could use it, but the syntax would be:

string str = String.Format("{0:Y}", dt);

      

hope this helps. The format specifier you are looking for is probably "MMMM yyyy", the default format for "Y" is year-month, not month-year. In the meantime, there is no need to worry about it.

+2


source


Try:

string dt1 = dt.ToString("MMMM yyyy");

      

+1


source


Try dt.ToString ("Y")

0


source







All Articles