简体   繁体   English

DateTime ToString(“dd / MM / yyyy”)返回dd.MM.yyyy

[英]DateTime ToString(“dd/MM/yyyy”) returns dd.MM.yyyy

I have also tried shielding the '/' symbol in the formatting string, but it didn't quite work. 我也尝试屏蔽格式化字符串中的'/'符号,但它不太起作用。 My final goal is to get the date with the '/' symbols as separators. 我的最终目标是使用'/'符号作为分隔符来获取日期。 I guess I can use DateTime.ToString(“dd/MM/yyyy”).Replace('.', '/') , but that feels a bit excessive. 我想我可以使用DateTime.ToString(“dd/MM/yyyy”).Replace('.', '/') ,但感觉有点过分。

The / character in date/time format strings stands for "whatever the date separator of the format provider is". 日期/时间格式字符串中的/字符代表“无论格式提供者的日期分隔符是什么”。 Since you do not supply a format provider Thread.CurrentCulture is used, and in your case the current culture uses . 由于您不提供格式提供程序,因此使用了Thread.CurrentCulture ,并且在您的情况下使用当前区域性. as the date separator. 作为日期分隔符。

If you want to use a literal slash, place it inside single quotes: 如果要使用文字斜杠,请将其放在单引号内:

dateTime.ToString("dd'/'MM'/'yyyy");

Alternatively, you could specify a format provider where the date separator is / : 或者,您可以指定日期分隔符为/的格式提供程序:

dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

All of the above is documented on MSDN . 所有上述内容都记录在MSDN上

See the difference in a live example . 查看实例中的差异

string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)

This is because of the way ToString works by default , in accordance with the current culture: 这是因为默认情况下ToString工作方式符合当前的文化:

This method uses formatting information derived from the current culture. 此方法使用从当前文化派生的格式信息。

So, override that: 所以,覆盖:

string date = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)

This works (note the InvariantCulture ): 这有效(注意InvariantCulture ):

DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)

If a CultureInfo is not specified, the CurrentCulture will be used. 如果未指定CultureInfo ,则将使用CurrentCulture If this is a culture that doesn't use slashes as separators in dates it is replaced by whatever the actual culture date separator is. 如果这是一种不在日期中使用斜杠作为分隔符的文化,则它将替换为实际的文化日期分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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