.net DateTime.Now.ToShortDateString(); 替换月和日

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2182093/
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-09-03 13:51:33  来源:igfitidea点击:

DateTime.Now.ToShortDateString(); replace month and day

.netdatetimedatetime-format

提问by cnd

I need to change format of

我需要改变格式

this.TextBox3.Text = DateTime.Now.ToShortDateString();

so it returns (for example) 25.02.2012, but I need 02.25.2012

所以它返回(例如)25.02.2012,但我需要02.25.2012

How can this be done?

如何才能做到这一点?

回答by jason

Use DateTime.ToStringwith the specified formatMM.dd.yyyy:

使用DateTime.ToString指定的格式MM.dd.yyyy

this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");

Here, MMmeans the month from 01 to 12, ddmeans the day from 01 to 31 and yyyymeans the year as a four-digit number.

此处,MM表示从 01 到 12 的月份,dd表示从 01 到 31 的日,以及yyyy表示为四位数的年份。

回答by bniwredyc

Little addition to Jason's answer:

杰森回答的一点补充:

  1. The ToShortDateString()is culture-sensitive.
  1. ToShortDateString()是文化敏感。

From MSDN:

来自 MSDN:

The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.

ToShortDateString 方法返回的字符串区分区域性。它反映了当前区域性的 DateTimeFormatInfo 对象定义的模式。例如,对于 en-US 文化,标准的短日期模式是“M/d/yyyy”;对于 de-DE 文化,它是“dd.MM.yyyy”;对于 ja-JP 文化,它是“yyyy/M/d”。还可以自定义特定计算机上的特定格式字符串,使其不同于标准的短日期格式字符串。

That's mean it's better to use the ToString()method and define format explicitly (as Jason said). Although if this string appeas in UI the ToShortDateString()is a good solution because it returns string which is familiar to a user.

这意味着最好使用该ToString()方法并明确定义格式(如 Jason 所说)。虽然如果这个字符串出现在 UI 中,这ToShortDateString()是一个很好的解决方案,因为它返回用户熟悉的字符串。

  1. If you need just today's date you can use DateTime.Today.
  1. 如果您只需要今天的日期,您可以使用DateTime.Today.

回答by Hogan

this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");

回答by mark

this.TextBox3.Text = String.Format("{0: MM.dd.yyyy}",DateTime.Now);

this.TextBox3.Text = String.Format("{0: MM.dd.yyyy}",DateTime.Now);