Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get today's date in C# in mm/dd/yyyy format?

Tags:

date

c#

How do I get today's date in C# in mm/dd/yyyy format?

I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time.

BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11.

Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well.

kronoz's answer

like image 368
Keng Avatar asked Aug 28 '08 16:08

Keng


2 Answers

DateTime.Now.ToString("M/d/yyyy");

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

like image 146
Joel Coehoorn Avatar answered Sep 24 '22 17:09

Joel Coehoorn


Not to be horribly pedantic, but if you are internationalising the code it might be more useful to have the facility to get the short date for a given culture, e.g.:-

using System.Globalization;
using System.Threading;

...

var currentCulture = Thread.CurrentThread.CurrentCulture;
try {
  Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-us");
  string shortDateString = DateTime.Now.ToShortDateString();
  // Do something with shortDateString...
} finally {
  Thread.CurrentThread.CurrentCulture = currentCulture;
}

Though clearly the "m/dd/yyyy" approach is considerably neater!!

like image 29
ljs Avatar answered Sep 23 '22 17:09

ljs