如何以 mm/dd/yyyy 格式在 C# 中获取今天的日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 09:12:55  来源:igfitidea点击:

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

提问by Keng

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

如何以 mm/dd/yyyy 格式在 C# 中获取今天的日期?

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.

顺便说一句:我在美国,所以 M/dd 是正确的,例如 9 月 11 日是 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 的回答是在讨论国际化时提出的,我认为提及它已经足够棒了,因为我也不能将其作为“可接受”的答案。

kronoz's answer

克罗诺兹的回答

回答by Corin Blaikie

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

回答by Josh Mein

DateTime.Now.Date.ToShortDateString()

I think this is what you are looking for

我想这就是你要找的

回答by Corin Blaikie

DateTime.Now.Date.ToShortDateString()

is culture specific.

是特定于文化的。

It is best to stick with:

最好坚持:

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

回答by EBGreen

Or without the year:

或者没有年份:

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

回答by FlySwat

If you want it without the year:

如果你想要没有年份:

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

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

DateTime.ToString() 有很多很酷的格式字符串:

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

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

回答by Billy Jo

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

回答by ljs

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

尽管显然“m/dd/yyyy”方法要简洁得多!!