Format C# DateTime
I have a bit of code that display the date within a text field as shown below
textField.Text = DateTime.Now.ToShortDateString();
It shows as
1开发者_JAVA百科1/03/2011
anyone know how I could format here to show it as
11/03/11
Thanks in advance
Yes. Take a look at this Date and Time formatting page.
Or: theDate.ToString("dd/MM/yy")
Very simple:
string strFormat = "dd/MM/yy";
textField.Text = DateTime.Now.ToString(strFormat);
note that the format string is case-sensitive, make sure you use capital 'M's for month, otherwise it will consider 'minutes' for 'm'. More general help about datetime formatting:
- MMM: display three-letter month
- MM: display two-digit month
- ddd: display three-letter day of the WEEK
- d: display day of the MONTH
- HH: display two-digit hours on 24-hour scale
- mm: display two-digit minutes
- yyyy: display four-digit year
DateTime.Now.ToString("dd/MM/yy")
DateTime.Now.ToString("dd/MM/yy")
But you need to remember that ToShortDateString()
is culture sensitive, returning different strings depending on the regional settings of the computer - the above is not.
You could change the settings on your computer, in Windows 7, you will find the Short Date format under Region and Language
in the control panel.
Here is an alternative if you don't like format strings.
var fp = new System.Globalization.CultureInfo("en-GB");
textField.Text = DateTime.Now.ToString(fp.DateTimeFormat.ShortDatePattern);
精彩评论