简体   繁体   中英

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

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, eg 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

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

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

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, eg:-

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!!

DateTime.Now.ToString("dd/MM/yyyy");
DateTime.Now.Date.ToShortDateString()

is culture specific.

It is best to stick with:

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

If you want it without the year:

DateTime.Now.ToString("MM/DD");

DateTime.ToString() has a lot of cool format strings:

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

string today = DateTime.Today.ToString("M/d");
DateTime.Now.Date.ToShortDateString()

我想这就是你要找的东西

或者没有年份:

DateTime.Now.ToString("M/dd")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM