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
Muntasir
source
to share
6 answers
DateTime dt = Convert.ToDateTime(dateTimePicker1.Text); //taken the DateTime from form
string dt1 = dt.ToString("MMMM yyyy")
+5
Gordon bell
source
to share
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
Trevor
source
to share
You have other answers that use ToString
.. If you want to use string.Format
, try this:
string dt1 = string.Format("{0:Y}", dt);
+2
Ben M
source
to share
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
Thorarin
source
to share
Try:
string dt1 = dt.ToString("MMMM yyyy");
+1
Callum rogers
source
to share
Try dt.ToString ("Y")
0
Eddie velasquez
source
to share