C-sharing-guy
C-sharing-guy

Reputation: 61

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

11/03/2011

anyone know how I could format here to show it as

11/03/11

Thanks in advance

Upvotes: 3

Views: 9134

Answers (5)

Bob
Bob

Reputation: 99714

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

Upvotes: 2

John Gietzen
John Gietzen

Reputation: 49544

DateTime.Now.ToString("dd/MM/yy")

Upvotes: 3

mdm
mdm

Reputation: 12630

Yes. Take a look at this Date and Time formatting page.

Or: theDate.ToString("dd/MM/yy")

Upvotes: 12

DeveloperInToronto
DeveloperInToronto

Reputation: 1193

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

Upvotes: 3

Chris Diver
Chris Diver

Reputation: 19812

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.

Upvotes: 2

Related Questions