C# DateTime ToString(“dd/MM/yyyy”) 返回 dd.MM.yyyy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15273215/
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
DateTime ToString(“dd/MM/yyyy”) returns dd.MM.yyyy
提问by Джавид Бунят-заде
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('.', '/')
,但这感觉有点过分。
采纳答案by Jon
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 .
as the date separator.
该/
日期/时间格式字符串的字符表示“无论格式提供的日期分隔符为”。由于您没有提供格式提供程序Thread.CurrentCulture
,因此在您的情况下,当前文化.
用作日期分隔符。
If you want to use a literalslash, 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 上。
回答by Brian P
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)
回答by Tim Schmelter
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. 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.
如果CultureInfo
未指定 a,CurrentCulture
则将使用 。如果这是一种在日期中不使用斜杠作为分隔符的文化,它将被替换为实际的文化日期分隔符。
回答by Grant Thomas
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)